繁体   English   中英

无法从JAR加载属性

[英]Can't load Properties from 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");
    }

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

如果getClass()返回的是由类加载器加载的类,而不是将jar放在其类路径中的类加载器,则可能会产生特殊性。

您也可以尝试-

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

我有一个简单的控制台应用程序遇到了同样的问题。 最终,我在https://stackoverflow.com/a/1464541/1792291上找到了一个提示,并将控制台应用程序变成了swing应用程序,突然一切正常。

上面的链接中的解释确实有道理:由于控制台应用程序在创建外壳程序后即获得其属性(包括CLASSPATH),因此它不知道JVM期间/为/由JVM定义的类路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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