Reading from a configuration file outside the Java Jar

I am currently trying to read my configuration file from the project root directory to make this actual configuration, I want to move it to an external location and then read from there.

Adding the full path to the following code throws an error:

package CopyEJ; import java.util.Properties; public class Config { Properties configFile; public Config() { configFile = new java.util.Properties(); try { // configFile.load(this.getClass().getClassLoader().getResourceAsStream("CopyEJ/config.properties")); Error Statement ** configFile.load(this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties")); }catch(Exception eta){ eta.printStackTrace(); } } public String getProperty(String key) { String value = this.configFile.getProperty(key); return value; } } 

Here's the error:

 java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:365) at java.util.Properties.load(Properties.java:293) at CopyEJ.Config.<init>(Config.java:13) at CopyEJ.CopyEJ.main(CopyEJ.java:22) Exception in thread "main" java.lang.NullPointerException at java.io.File.<init>(File.java:194) at CopyEJ.CopyEJ.main(CopyEJ.java:48) 

How can i fix this?

+4
source share
2 answers

The purpose of the getResourceAsStream method is to open a stream in some file that exists inside your bank. If you know the exact location of a particular file, just open a new FileInputStream .

those. your code should look like this:

 try (FileInputStream fis = new FileInputStream("C://EJ_Service//config.properties")) { configFile.load(fis); } catch(Exception eta){ eta.printStackTrace(); } 
+6
source

This line requires your config.properties be in java CLASSPATH

 this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties") 

If this is not the case, config.properties will not be available.

You can try another alternative and use the configFile.load() function to read.

One example would be:

 InputStream inputStream = new FileInputStream(new File("C:/EJ_Service/config.properties")); configFile.load(inputStream); 
+3
source

Source: https://habr.com/ru/post/1489260/


All Articles