Relative path to database file in Java - java

I have to access a database file in my Java project but I can't get the path right.
The full path is C:\Hogwarts\db\hogdb.fdb.
I tried to use this code line to find the the current relative path:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
and it says the current relative path is: C:\Hogwarts.
Right now my code looks like this :
minDataBas = new InfDB("db\\HOGDB.FDB");
new HuvudFonster(minDataBas).setVisible(true);
What am I missing?

In fact all elements are there; just use an absolute path.
String cwd = System.getProperty("user.dir"); // Alternative
Path cwdPath = Paths.get(cwd);
Path dbPath = Paths.get(cwd, "db/hogdb.fdb");
String db = dbPath.toAbsolutePath().toString();
if (!Files.exists(dbPath)) {
throw new IllegalStateException("Wrong path for database: " + db);
}
minDataBas = new InfDB(db);

From the InfDB.java file:
#param path Path to the Firebird DB, for example C:/DB.FDB or for Mac /User/DB.FDB
Providing the absolute path, as opposed to relying on the method inferring you are using a relative path, should resolve the issue. Hence, use:
minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");
or if you know that the database file will be similarly relative to the current working directory for wherever it has launched, you could use the previously found working directory path and append the remaining location as such
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
minDataBas = new InfDB(s + "\\db\\HOGDB.FDB");
If you cannot be sure where the file will there are a variety of techniques you could use to have the user define where the file is. Setting a path variable, configuration files or simply taking user input.

I think instead it should be
minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");

Related

Get path of file without drive letter - Windows 10 / Java 8

Windows 10
Java 8
When I call getCanonicalPath on a File object, I get a string like this
C:\data\processed\Test.xml
How do I get the same string but without C:\ and if possible also with / instead of \?
You can use NIO.2 API and its objects Path and Paths which is a abstraction over a file system.
Path path = Paths.get("C:\\data\\processed\\Test.xml");
You can also get Path from File using File::toPath. Actually, you need to get all the names in the path:
File file = new File("C:\\data\\processed\\Test.xml");
Path path = file.toPath();
int count = path.getNameCount(); // the count of names
path = path.subpath(0, count); // all the names
Alternatively (thanks to #Holger) using Path:relativize (you find a relative path to the root C:/ which is all the names.
File file = new File("C:\\data\\processed\\Test.xml");
Path path = file.toPath();
path = path.getRoot().relativize(path);
Here are some relevant methods:
path.getRoot() returns C:\
path.getNameCount() returns the number of name elements in the path (3 in this case)
path.getName(0) returns data, path.getName(1) returns processed etc...
path.subpath(fromInclusive, toExclusive) returns a relative Path that is a subsequence of the name elements of this path.
path.relativize(path) returns a relative path to a parameter.
The object Path represents an abstraction of the actual path. If you want to replace \ with / as a String, you might need to use String::replace.
String stringPath = path.toString().replace('\\', '/');
System.out.println(path); // data\processed\Test.xml
System.out.println(stringPath); // data/processed/Test.xml
Here is a short answer:
File file = new File("c:\\tmp\\abc.txt"); //file =C:\tmp\abc.txt
String filePath= file.getCanonicalPath(); //path= C:\tmp\abc.txt
String str=filePath.replace('\\', '/'); //str= C:/tmp/abc.txt
java.net.URI uri= new java.net.URI(str); //uri= C:/tmp/abc.txt
uri.getPath(); //uri.getPath() = /tmp/abc.txt

How to get path to package in Eclipse (Java)

I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");

Setting system property to a file path

I am trying to set System.setProperty to a file path:
//properties key
String propFile = "propertiesFile";
String pathToFile = "properties/prop.properties";
File file = new file(pathToFile);
//properties value
String path = file.getAbsolutePath();
System.setProperty(propFile, path);
//using properties.....
And I am getting FileNotFoundException.
when printing the file I get the absolutePath - c:\Project...\prop.properties
Is setting System.setProperty should be done another way?
the properties - package inside src.
Your problem is not related to the method System.setProperty as your path is managed as any other String, your problem is more that new File(pathToFile) refers to a non existing file as you provide a relative path and the absolute path is created from the user directory (value of System.getProperty("user.dir")) which is probably not what you expect. If you call new File(pathToFile).exists() it will return false check the resulting path first.

Relative file path in java

I have this code:
Process p = Runtime.getRuntime().exec(command.toString(), null,
new File("D:\\Cognity"));
But the thing is the Cognity directory is not always in D:\, it could be in C:\ etc. So my question is if there is a way to give it a relative path so I don't have to change this code depending on the PC that uses the program?
As System.getProperty("user.dir")); returns the directory from which the JVM was launched you still can't guarantee whether you're in C:\ or D:\
My advice would be to pass the Cognity location in as a -D commandline argument and use it like this:
Process p = Runtime.getRuntime().exec(command.toString(), null, new File(System.getProperty("cognity.dir")));
Call System.getProperty("user.dir"); to get your current dir, and concat the relative path to the result.
e.g.
String path = System.getProperty("user.dir");
path += relativePath;
EDIT:
Clarification:
For example:
The program you want to run is always located two folders backwards, and then at Temp dir.
So the relative path is ..\\..\Temp\prog.exe.
Let's say that in one computer you have your program located at C:\Users\user\Documents\Program, so this is the working directory.
So:
String path = System.getProperty("user.dir"); //returns the working directory
String relativePath = "\\ ..\\..\\Temp"; //no matter what is the first path, this is the relative location to the current dir
path += relativePath;
//in this example, path now equals C:\Users\user\Documents\Program\..\..\Temp\prog.exe = C:\Users\user\Temp\prog.exe
Process p = Runtime.getRuntime().exec(command.toString(), null, new File(path));
You could use a config-File to set the absolute-path or you create that directory in a relative path to the jar-file.

Get the filePath from Filename using Java

Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...

Categories