简体   繁体   中英

Cannot load properties from jar

I have small app and I tested and packed to jar and am trying to run it but I have error.

Here is my project structure:

src
  -kie.template
  ----- ServerMain.java   ==> Class with main
  -kie.template.util
  ---- PropUtils.java
  ---- server.properties
target
  -kietemplate.jar
  ---- lib

In the main method, PropUtils class reads properties.

public class PropUtils {

    private static final String PROPERTIES = "server.properties";

    public static Properties load() {
    Properties properties = new Properties();
            InputStream is = null;
            try {
                properties.load(PropUtils.class.getResourceAsStream(PROPERTIES));

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is!=null) try{is.close();}catch(IOException e){}
            }

            return properties;
        }
     }
}

When I run the ServerMain class directly, it works fine. But after I packed it to jar and run, it shows error:

java -cp lib -jar kietemplate.jar

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 au.org.jeenee.kie.template.util.PropUtils.load(PropUtils.java:26)

The properties file is in the directory when I look into the jar file. jar tf kietemplate.jar

Any help would be appreciated very much.

EDIT: I changed the logic to read properties:

Properties properties = new Properties();
InputStream is = null;
try {
    File file = new File("server.properties");
    is = new FileInputStream(file);
    properties.load(new InputStreamReader(is));
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (is!=null) try{is.close();}catch(IOException e){}
}

It requires the properties file in parent directory of the jar file.

Your code works fine on my computer, both from the JAR and the filesystem.

A possible cause for that behaviour is the filesystem being case insensitive, but the jar file being case sensitive. But we really can't tell from the source code alone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM