[英]Cannot load properties from jar
我有一個小型應用程序,我測試並打包到jar中,並試圖運行它,但出現錯誤。
這是我的項目結構:
src
-kie.template
----- ServerMain.java ==> Class with main
-kie.template.util
---- PropUtils.java
---- server.properties
target
-kietemplate.jar
---- lib
在main方法中,PropUtils類讀取屬性。
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;
}
}
}
當我直接運行ServerMain類時,它可以正常工作。 但是在將其打包到jar並運行后,它顯示錯誤:
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)
當我查看jar文件時,屬性文件位於目錄中。 jar tf kietemplate.jar
任何幫助將不勝感激。
編輯:我更改了邏輯以讀取屬性:
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){}
}
它需要jar文件的父目錄中的屬性文件。
在JAR和文件系統上,您的代碼都可以在我的計算機上正常工作。
該行為的可能原因是文件系統不區分大小寫,但jar文件區分大小寫。 但是我們真的不能僅從源代碼中分辨出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.