0

I have properties file in my application's classpath. Before creating jar file for this application there is no problem but when I create jar file and run it using java -jar command it returns null pointer exception. Here is my code to load properties:

private Properties loadProperties() {
    Properties prop = new Properties();
    InputStream input = null;

    try {
        input = this.getClass().getResourceAsStream("./auth");
        prop.load(input);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return prop;
}

Can I access property file within jar or it is not possible?

Here is exception I get:

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.kadir.MyApp.loadProperties(MyApp.java:109)
    at com.kadir.MyApp.<init>(MyApp.java:62)
    at com.kadir.MyApp.main(MyApp.java:48)

and lines 108 and 109 are these:

    input =this.getClass().getClassLoader().getResourceAsStream("auth");
    prop.load(input);

One more note: I am developing my app on Windows but running it on Linux, error may come from this

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
kadir
  • 589
  • 1
  • 7
  • 29

1 Answers1

0

I don't know the exact reason for why it wasn't working but changing these two lines

input = this.getClass().getResourceAsStream("auth");
prop.load(input);

to these:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
input = classloader.getResourceAsStream("auth");
prop.load(input);

made my code working

kadir
  • 589
  • 1
  • 7
  • 29