user2385057
user2385057

Reputation: 537

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 ?

Upvotes: 4

Views: 11373

Answers (2)

SSaikia_JtheRocker
SSaikia_JtheRocker

Reputation: 5063

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);

Upvotes: 3

Andremoniy
Andremoniy

Reputation: 34920

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();
}

Upvotes: 7

Related Questions