Tutorial :Using relative directory path in Java


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?


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.


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");



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

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


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.


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.


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
Next Post »