22

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?

2
  • Define fails. What error messages are you getting? Are you using the correct path separator for your OS (there's a Java system variable for path separator that you should be using)? Commented Jul 15, 2009 at 13:48
  • What is your current directory and where is that file absolutely? Commented Jul 15, 2009 at 13:49

6 Answers 6

42

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

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

Comments

0

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.

Comments

0

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.

2 Comments

I don't know the other platforms, but on WinXP+ and Linux, using the forward slash seems to work. But +1 for File.separator.
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.
0

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.