简体   繁体   中英

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.

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. It uses quartz.properties file from classpath automatically.

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:

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. What is the best way to achieve this?

You have access to the command-line args in 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:

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

Check the API .

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

PS. use try-with-resources so you don't leak the stream like I do, above, and add error handling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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