[英]load external file from command prompt instead of using from classpath
我正在使用Maven項目,並且在/src/main/resources
文件夾中有一個quartz.properties
文件。
現在,可以從此類中以兩種方式使用此屬性文件,如下所示:
/**
* 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);
}
現在,我使用maven-shade-plugin
制作了一個可執行jar,並且在我的ubuntu框中以java -jar abc.jar
身份運行,並且工作正常。 它會自動使用classpath中的quartz.properties
文件。
public static void main(String[] args) {
StdSchedulerFactory factory = new StdSchedulerFactory();
try {
factory.initialize(App.class.getClassLoader().getResourceAsStream("quartz.properties"));
Scheduler scheduler = factory.getScheduler();
scheduler.start();
} catch (SchedulerException ex) {
System.out.println("error= " + ex);
}
}
現在,我試圖通過運行上面的jar文件時從命令提示符處傳遞quartz.properties
文件,使該程序更通用,如下所示:
java -jar abc.jar quartz.properties
如果我像上面那樣,那么它應該使用我傳遞的,而不是從類路徑傳遞的quartz.properties
文件,但是如果沒有傳遞任何參數,則應該使用默認的quartz.properties
文件。 實現此目標的最佳方法是什么?
您可以訪問main
的命令行參數:
if(args.length > 0) {
...
factory.initialize(args[0]);
} else {
...
factory.initialize(App.class.getClassLoader().getResourceAsStream("quartz.properties"));
}
如果沒有采用String
initialize
方法,則可以根據參數構造FileInputStream
:
factory.initialize(new FileInputStream(new File(args[0])));
檢查API 。
props.load( new FileInputStream("quartz.properties") );
PS。 使用try-with-resources,這樣您就不會像我上面那樣泄漏流,並添加錯誤處理
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.