从命令提示符加载外部文件而不是使用类路径

load external file from command prompt instead of using from classpath

我正在使用 Maven 项目,我在 /src/main/resources 文件夹中有一个 quartz.properties 文件。

现在我可以从这个 class 以两种方式使用这个 属性 文件,如下所示:

/**
 * 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 并且它工作正常。它自动使用 class 路径中的 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);
    }
}

现在我试图通过从命令提示符传递 quartz.properties 文件来使这个程序更通用,而 运行 我上面的 jar 文件如下所示:

java -jar abc.jar quartz.properties

如果我像上面那样,那么它应该使用 quartz.properties 文件我传递的而不是来自 classpath 但是如果没有传递参数那么它应该使用默认值 quartz.properties 文件。实现此目标的最佳方法是什么?

检查API

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

PS。使用 try-with-resources 这样你就不会像我上面那样泄漏流,并添加错误处理

您可以访问 main 中的命令行参数:

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

如果没有接受 Stringinitialize 方法,那么您可以从参数构造一个 FileInputStream

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