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...
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
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With