无法从JAR加载属性

时间:2011-08-02 20:03:59

标签: java properties jar

几天后,我一直试图让我的Java项目从位于其JAR文件中的文件加载一些属性。但是,在尝试加载文件时,我经常会得到一个空指针。

文件夹层次结构在/ data中包含属性文件,在/ emp / ** / **中包含所有源文件...

代码

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

3 个答案:

答案 0 :(得分:3)

如果data位于jar的根目录中,并且build_info.properties位于jar中的数据目录中,并且jar位于类路径中,那么getClass().getClassLoader().getResourceAsStream("data/build_info.properties");将会找到那个属性文件。您也可以使用getClass().getResourceAsStream("/data/build_info.properties");

如果getClass()返回由类加载器加载的类不同于在类路径上具有jar的类,则会出现特殊情况。

答案 1 :(得分:1)

您也可以尝试 -

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

答案 2 :(得分:0)

我遇到了一个死机简单的控制台应用程序的问题。最后我在https://stackoverflow.com/a/1464541/1792291找到了一个提示,我将我的控制台应用程序变成了一个摇摆应用程序,突然一切都运转了。

上面链接中的解释确实有一定道理:由于控制台应用程序在创建shell时获取其属性(包括CLASSPATH),因此它不会知道在JVM期间/ for /中定义的类路径。 / p>

相关问题