Tutorial :Using relative directory path in Java



Question:

I am trying to use a relative path to locate an executable file within a Java class instead of hard-coded lines which worked, but using something like:

final static String directory = "../../../ggla/samples/obj/linux_x86"

fails... what is the proper way of using a relative path in Java?


Solution:1

The most likely explanation is that your current directory is not where you think that it is. You can inspect the system property of user.dir to see what the base path of the application is, or you can do something like this:

 System.out.println(new File(".").getCanonicalPath());  

right before you use that relative path to debug where your relative reference starts.


Solution:2

Use System.out.println(System.getProperty("user.dir")); to see where your current directory is. You can then use relative paths from this address.

Alternatively if you dont need to update the file you are trying to read obtain it from the classpath using getResourceAsStream("filename");

Karl


Solution:3

What you need is getCanonicalPath or getCanonicalFile to resolve the relative paths.

System.out.println(new File("../../../ggla/samples/obj/linux_x86")      .getCanonicalPath());  


Solution:4

You can use relative paths like you describe, and it should work. So the error is probably somewhere else.

Please post a complete program to reproduce your error, then we may be able to help.


Solution:5

I would start by using the separator and path separator specified in the Java File class. However, as I said in my comment, I need more info than "it fails" to be of help.


Solution:6

For relative path, maybe you can use one of the method provide by java for the beginning of the relative path as getRelativePath.... You have to use / and not // in the String in java !


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »