Reputation: 1962
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/
Upvotes: 1
Views: 12482
Reputation: 718678
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.
Upvotes: 3
Reputation: 44740
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 (../)
Upvotes: 0
Reputation: 2242
Your current path.
currentPath= /home/username/project/src/com/xyz/;
Relative path to "/home/username/project/secure/" folder is
relativePath= ../../../secure;
Upvotes: 2