开发者

Can't load Properties from JAR

For a few days now, I have been trying to get my Java project to load some properties from a file located in it's JAR file. However, I am constantly getting a null pointer when trying to load in the file.

The folder hierarchy has the properties file in /data, and all the source files in /emp/**/** ...

Code

Properties defaultProps = new Properties();
    try {
        InputStream in = getClass().getClassLoader().getResourceAsStream("data/build_info.properties");
        //InputStream in = new URL("file:data/build_info.properties").openStream();

        defaultProps.load(in);
        in.close();
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
    } catch (IOException e) {
        //e.printStackTrace();
    } catch (NullPointerException e){
        Log.E("NPE- Properties not loaded", "properties");
        revision = "Properties file not found";
    }

    if (defaultProps.getProperty("build.major.number") == null) {
        Log.W("Properties not loaded", "properties");
       开发者_高级运维 revision = "Properties file not found";
    } else {
        Log.V("Properties Loaded Successfully", "properties");
        
        revision = "Version: " + defaultProps.getProperty("build.major.number")
            + "." + defaultProps.getProperty("build.minor.number") + "    "
            + "Revision: "
            + defaultProps.getProperty("build.revision.number");
    }


If data is in the root of your jar, and if build_info.properties is inside the data directory in the jar, and if the jar is on the classpath, then getClass().getClassLoader().getResourceAsStream("data/build_info.properties"); will find that properties file. You could also use getClass().getResourceAsStream("/data/build_info.properties");.

Peculiarities can arise if getClass() returns a class loaded by a classloader different than the one that has your jar on its classpath.


You could alternatively try --

Thread.currentThread().getContextClassLoader().getResourceAsStream("data/build_info.properties");


I had the same issue with a dead-simple console application. Eventually I found a hint at https://stackoverflow.com/a/1464541/1792291 and I made my console app into a swing app, and suddenly everything worked.

The explanation in the link above does make some sense: since the console app gets its properties (including CLASSPATH) once when the shell is created, it won't know about the classpath defined during/for/by the JVM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜