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/
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
comatose
  • 1,952
  • 7
  • 26
  • 42
  • 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. – ping Jun 29 '12 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 – Jakob Weisblat Jun 29 '12 at 10:08

3 Answers3

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.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Your current path.

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

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

relativePath= ../../../secure;
Akhi
  • 2,242
  • 18
  • 24
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 (../)

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111