JVerstry JVerstry - 2 months ago 10
Java Question

Property file won't load in static code, getting NullPointerException

I am trying to load a property file in Java in static initialization code:

public class NFWConfiguration {

private static final Properties PROPS = new Properties();

static {
try {

InputStream IS = NFWConfiguration.class.getClassLoader()
.getResourceAsStream(
"/net/nfw/Configuration/NFWConfiguration.properties");

PROPS.load(IS);

} catch (IOException ex) {
Logger.getLogger(NFWConfiguration.class.getName())
.log(Level.SEVERE, null, ex);
}
}

// ...

}


Yet, I get the following error message:

Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at net.nfw.Configuration.NFWConfiguration.<clinit>(NFWConfiguration.java:28)


Indeed
IS
is
null
, but it has no reason to be
null
. I have double-checked in the
.jar
, and the property file is there in the right directory.

What am I doing wrong?

Answer

Try after removing the leading / in the path as:

      InputStream IS = NFWConfiguration.class.getClassLoader()
        .getResourceAsStream(
            "net/nfw/Configuration/NFWConfiguration.properties");