tags:

views:

685

answers:

6

Hello, 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?

A: 

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.

sleske
A: 

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.

Thomas Owens
I don't know the other platforms, but on WinXP+ and Linux, using the forward slash seems to work. But +1 for File.separator.
kd304
I'm usually lazy in my personal apps and use the forward slash, but in production code (at work), I convert everything to using the separator and pathSeparator in File.
Thomas Owens
A: 

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 !

Matthieu
+1  A: 

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

Karl
+3  A: 

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.

Yishai
great info thanks!
+1  A: 

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

System.out.println(new File("../../../ggla/samples/obj/linux_x86")
    .getCanonicalPath());
bruno conde
great info thanks!