[英]not able to load properties file with runnable jar
我有一個Java的Maven項目,在這個目錄下有一個屬性文件(quartz.properties):
/src/main/resources
現在,可以從此類中以兩種方式使用此屬性文件,如下所示:
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(Properties)}</code>.
*
* @see #initialize(Properties)
*/
public StdSchedulerFactory(Properties props) throws SchedulerException {
initialize(props);
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(String)}</code>.
*
* @see #initialize(String)
*/
public StdSchedulerFactory(String fileName) throws SchedulerException {
initialize(fileName);
}
所以我開始這樣使用:
public static void main(String[] args) {
StdSchedulerFactory factory = new StdSchedulerFactory();
try {
factory.initialize(TestClassName.class.getClassLoader().getResourceAsStream("quartz.properties"));
Scheduler scheduler = factory.getScheduler();
scheduler.start();
} catch (SchedulerException ex) {
System.out.println("error= " + ExceptionUtils.getStackTrace(ex));
}
}
這在我的Windows筆記本電腦中運行正常,沒有任何問題,但是當我制作一個可運行的jar(導出->可運行的jar->將所需的庫打包到生成的JAR中)之后,然后在其他ubuntu機器上像這樣運行時:
java -jar abc.jar
我收到此異常:
error= org.quartz.SchedulerException: Error loading property data from InputStream - InputStream is null.
at org.quartz.impl.StdSchedulerFactory.initialize(StdSchedulerFactory.java:576)
at com.example.quartz.TestClassName.main(TestClassName.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
我在做什么錯?
更新: jar tvf abc.jar
輸出。 我只是展示有關的東西,而不是全部。
13 Thu Sep 10 18:16:30 GMT-07:00 2015 resources/build.properties
594 Thu Sep 10 18:16:30 GMT-07:00 2015 resources/quartz.properties
1254 Thu Sep 10 18:16:30 GMT-07:00 2015 resources/quartz_config.xml
您的文件在jar文件中的名稱是resources/quartz.properties
,而不僅僅是quartz.properties
,因此您需要這樣加載它:
factory.initialize(
TestClassName.class.getClassLoader().getResourceAsStream("resources/quartz.properties"));
或者,以其他方式創建jar文件,以使quartz.properties
位於jar文件的“根”目錄中。 (鑒於您所描述的文件系統結構,這正是我所期望的。)
如果要從類訪問resources/build.properties
,則需要使用絕對路徑,如下所示:
TestClassName.class.getClassLoader().getResourceAsStream("/resources/quartz.properties")
首先,您應該確保jar文件中的quartz.properties。 如果不存在,則需要檢查pom.xml中的構建設置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.