relative path in Java

12,269

Solution 1

Your current path.

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

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

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

Solution 2

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.

Share:
12,269
comatose
Author by

comatose

I am a doing Masters in Software Engineering of Distributed Systems

Updated on June 04, 2022

Comments

  • comatose
    comatose almost 2 years

    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/
    
    • ping
      ping almost 12 years
      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.
    • Jakob Weisblat
      Jakob Weisblat almost 12 years
      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