Lawrence Park
Lawrence Park

Reputation:

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?

Upvotes: 22

Views: 83650

Answers (6)

bruno conde
bruno conde

Reputation: 48255

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

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

Upvotes: 1

Yishai
Yishai

Reputation: 91931

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.

Upvotes: 42

Karl
Karl

Reputation: 2955

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

Upvotes: 3

Matthieu
Matthieu

Reputation: 2761

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 !

Upvotes: 0

Thomas Owens
Thomas Owens

Reputation: 116187

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.

Upvotes: 0

sleske
sleske

Reputation: 83635

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.

Upvotes: 0

Related Questions