簡體   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