Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java relative file paths

Tags:

java

file

I've got a Java question that I've been having a trouble with: what is a good way to indicate relative file paths.

Let me be more specific. I want to be able to say to always look for configuration files in ./configuration/file.txt. The problem I'm having is that my program will only work correctly if it is started from the directory the file is in. If instead I start it from a different directory like ./directory/to/my/program/execute.sh then it fails to function correctly.

But I also need to make changes to this file, and resources seem to want to be read-only...

like image 842
Alex Baranosky Avatar asked Dec 26 '11 19:12

Alex Baranosky


3 Answers

The suggested (so that the app is independent of the environment specific details) way to read configuration information is to read it as a classpath resource rather than a file system resource. Read Smartly load your properties for more details.

Read Class.getResourceAsStream javadoc for syntax on how to specify the resource path

Useful post on SO: Classpath resource within jar

like image 139
Aravind Yarram Avatar answered Nov 14 '22 21:11

Aravind Yarram


You need to provide a mechanism for defining a directory, like through an environment variable, a command-line argument, config file, the preferences API, etc.

like image 44
Dave Newton Avatar answered Nov 14 '22 22:11

Dave Newton


To ensure your data is always in the same location you can make use of the home directory. Making use of the home directory will give you some consistency across different platforms and your program can access the data regardless of the directory it is in.

For example:

String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.collection";

And then you can retrieve a file later with something like

String fileLocation = systemDir + "/file.txt";
like image 29
Katana Avatar answered Nov 14 '22 21:11

Katana