简体   繁体   English

从命令提示符加载外部文件,而不是从classpath使用

[英]load external file from command prompt instead of using from classpath

I am working with maven project and I have a quartz.properties file in /src/main/resources folder. 我正在使用Maven项目,并且在/src/main/resources文件夹中有一个quartz.properties文件。

Now I can use this property file in two ways from this class as shown below: 现在,可以从此类中以两种方式使用此属性文件,如下所示:

/**
 * 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);
}

Now I have made an executable jar using maven-shade-plugin and I am running in my ubuntu box as java -jar abc.jar and it works fine. 现在,我使用maven-shade-plugin制作了一个可执行jar,并且在我的ubuntu框中以java -jar abc.jar身份运行,并且工作正常。 It uses quartz.properties file from classpath automatically. 它会自动使用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);
    }
}

Now I am trying to make this program more generic by passing quartz.properties file from the command prompt while running my above jar file as shown below: 现在,我试图通过运行上面的jar文件时从命令提示符处传递quartz.properties文件,使该程序更通用,如下所示:

java -jar abc.jar quartz.properties

If I do like above, then it should use quartz.properties file what I am passing and not from classpath but if there is no argument passed then it should use default quartz.properties file. 如果我像上面那样,那么它应该使用我传递的,而不是从类路径传递的quartz.properties文件,但是如果没有传递任何参数,则应该使用默认的quartz.properties文件。 What is the best way to achieve this? 实现此目标的最佳方法是什么?

You have access to the command-line args in main : 您可以访问main的命令行参数:

if(args.length > 0) {
   ...
   factory.initialize(args[0]);
} else {
   ...
   factory.initialize(App.class.getClassLoader().getResourceAsStream("quartz.properties"));
}

If there is no initialize method that takes a String , then you can constructor a FileInputStream from the argument: 如果没有采用String initialize方法,则可以根据参数构造FileInputStream

factory.initialize(new FileInputStream(new File(args[0])));

Check the API . 检查API

props.load( new FileInputStream("quartz.properties") );

PS. PS。 use try-with-resources so you don't leak the stream like I do, above, and add error handling 使用try-with-resources,这样您就不会像我上面那样泄漏流,并添加错误处理

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

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