1

My program has to use certain files that reside in another directory. Right now I am using absolute path to specify the location of the files. But I know that the relative position of these files will remain the same compared to where my program is residing. How I can use relative path in Java to specify the location of these files?

For example my program is residing in

/home/username/project/src/com/xyz/ 

..and the target files are in..

/home/username/project/secure/ 
2
  • Is adding these files to your project an option ? Loose files on the filesystem keep changing and absolute and relative pointers to them may not be a great idea if multiple entities read/write these files. Commented Jun 29, 2012 at 10:05
  • Are you using an IDE that runs your code from a different directory? eclipse would run that from /home/username/project, so the relative path there would be ./secure Commented Jun 29, 2012 at 10:08

3 Answers 3

3

For example my program is residing in /home/username/project/src/com/xyz/

and the target files are in /home/username/project/secure/

Knowing the place where your program's source code resides does not help. What you need to know is the current directory of the program when it is executed. That could be literally anything. Even if you are launching the application from (for example) Eclipse, the application launcher allows you to specify the "current directory" for the child process in the Run configuration.

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

Comments

2

Your current path.

 currentPath= /home/username/project/src/com/xyz/; 

Relative path to "/home/username/project/secure/" folder is

relativePath= ../../../secure; 

Comments

0

In Java you can use getParentFile() to traverse up the tree.

File currentDir = new File("."); File parentDir = currentDir.getParentFile(); 

This will be safe as you are not using system dependent file separator (../)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.