Reputation: 42957
I have the following problem trying to load a properties file from a directory that is external to my project.
So my project have the following structure:
PROJECT-ROOT
|
|
|-----> confi
|
|------> src
|
|
|------> mainPkg (the package name)
|
|
|------> Main (the main class containing the main() method)
Ok so into the main class I need to load the config.properties file situated outside the project root folder (for example at the same level). So I think that config.properties file is external to the application classpath.
So I tried to do something like this:
InputStream input = new FileInputStream("../../config.properties");
or
InputStream input = new FileInputStream("../../../config.properties");
but don't work because I obtain the following exception:
java.io.FileNotFoundException: ..\..\config.properties (Impossibile trovare il file specificato)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at mainPkg.Main.main(Main.java:41)
If I use an absolute path like this it works:
InputStream input = new FileInputStream("C:\\Projects\\edi-sta\\config.properties");
and correctly retrieve the InputStrea object. But this is not good for my purpose because I can't use absolute path.
How can I retrieve my config.properties file that is situated at the same level of the project root folder using relative path?
Upvotes: 0
Views: 6676
Reputation: 712
If the config.properties file is out of classpath you should use a folder as a starting point (for example user folder or current working folder).
Instead if the file is within your classpath you can try with this.class.getResourceAsStream or this.class.getClassLoader().getResourceAsStream().
In a simple context the difference between the two invokations is quite simple: this.class.getResoursceAsStream("config.properties") will return an InputStream if and only if the file is in the same package of class invoking the method.
Instead this.class.getClassLoader().getResourceAsStream("config.properites") will return the same InputStream only if the file is on the root of classpath. In this case you have to add "config" folder to the classpath
Upvotes: 2
Reputation: 51711
Your project root would be your programs's current working directory. So, you should try with
InputStream input = new FileInputStream("../config.properties");
This however is not the recommended setup. The file should be placed inside the project directory and should be jar'd appropriately if and when you publish your application.
Upvotes: 2