Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading From Config File Outside Jar Java

Currently I am trying to read my config file from root of project directory, in order to make this actual configuration I want to move this to external location and then read from there.

Adding a complete path in following code throws out 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 ?

like image 958
user2385057 Avatar asked Dec 26 '22 01:12

user2385057


2 Answers

The purpose of method getResourceAsStream is to open stream on some file, which exists inside your jar. If you know exact location of particular file, just open new FileInputStream.

I.e. your code should look like:

try (FileInputStream fis = new FileInputStream("C://EJ_Service//config.properties")) {
     configFile.load(fis);
} catch(Exception eta){
     eta.printStackTrace();
}
like image 122
Andremoniy Avatar answered Jan 12 '23 14:01

Andremoniy


This line requires your config.properties to be in the java CLASSPATH

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

When it is not, config.properties won't be accessible.

You can try some other alternative and use the configFile.load() function to read from.

One example would be:

InputStream inputStream = new FileInputStream(new File("C:/EJ_Service/config.properties"));

configFile.load(inputStream);
like image 40
SSaikia_JtheRocker Avatar answered Jan 12 '23 14:01

SSaikia_JtheRocker