使用外部属性文件执行jar [英] Execute a jar with an external properties file

查看:140
本文介绍了使用外部属性文件执行jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有main-class的jar,可以执行如下:java -jar test.jar

I have a jar with main-class which can be executed like: java -jar test.jar

在jar里面我有类似

public static void main(String[] args) throws IOException {
    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("config.properties");
    Properties prop = new Properties();
    prop.load(is);
    //then I wanna fetch all the properties in the config.properties file
}

我同时运行:


  1. java -jar test.jar

  1. java -jar test.jar

java -jar test.jar -cp / tmp(其中config.properties所在的位置)

java -jar test.jar -cp /tmp (where config.properties is located)

java -jar test.jar -cp /tmp/config.properties(显然它不起作用,但是让我知道我想在这里实现的目标)

java -jar test.jar -cp /tmp/config.properties (obviously it doesn't work, but give you the idea what I am trying to achieve here)

代码不起作用,虽然我将config.properties文件的路径放在$ PATH和$ CLASSPATH下,但三者都抛出了NPE。

The code didn't work, all three throw NPE although I put the path of the config.properties file under my $PATH and $CLASSPATH.

重点是,从长远来看,我会将配置文件放在$ {my-config-path}中,然后正确读取/处理它。但在时间上我只想要快速而肮脏的东西。

The point is that, in long run, I will put the configuration file in ${my-config-path}, and read/handle it properly. But temporally I just want something quick and dirty.


  1. 我不想在我的jar中包含属性文件。

  2. 我想保留它在类路径或路径的外部,当我执行jar时,它找到它没有问题。


推荐答案

一旦指定 -jar 忽略所有类路径选项。

Once you specify -jar all classpath options are ignored.

而是指定默认配置位置(如在用户的主目录中)并允许在命令行上覆盖。

Instead, specify a default config location (like in user's home directory) and allow overriding on the command line.

有各种命令行解析选项,最简单的带有选项信息的注释类属性,例如,长选项和短选项名称,用法等。

There are a variety of command line parsing options, the easiest annotate class properties with option information, e.g., the long and short option names, usage, etc.

或使用 -D 选项并检索相应的系统属性。

Or use a -D option and retrieve the appropriate system property.

另一个选项是偏好设置 API。

Another option is the Preferences API.

这篇关于使用外部属性文件执行jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆