【问题标题】:How to override the properties file value through command line arguments?如何通过命令行参数覆盖属性文件值?
【发布时间】:2015-02-21 01:13:21
【问题描述】:

我有一个像这样的属性文件 -

hostName=machineA.domain.host.com
emailFrom=tester@host.com
emailTo=world@host.com
emailCc=hello@host.com

现在我正在从我的 Java 程序中读取上述属性文件 -

public class FileReaderTask {
    private static String hostName;
    private static String emailFrom;
    private static String emailTo;
    private static String emailCc;

    private static final String configFileName = "config.properties";
    private static final Properties prop = new Properties();

    public static void main(String[] args) {
        readConfig(arguments);
    }

    private static void readConfig(String[] args) throws FileNotFoundException, IOException {
        if (!TestUtils.isEmpty(args) && args.length != 0) {
            prop.load(new FileInputStream(args[0]));
        } else {
            prop.load(FileReaderTask.class.getClassLoader().getResourceAsStream(configFileName));
        }

        hostName = prop.getProperty("hostName").trim();         
        emailFrom = prop.getProperty("emailFrom").trim();
        emailTo = prop.getProperty("emailTo").trim();
        emailCc = prop.getProperty("emailCc").trim();
    }
}

大多数时候,我会通过命令行将上面的程序作为可运行的 jar 运行,就像这样 -

java -jar abc.jar config.properties

我的问题是 -

  • 有什么方法可以通过命令行覆盖属性文件中的上述属性,而无需在需要时触及文件?因为我不想在需要更改任何属性值时始终修改我的 config.properties 文件?这可能吗?

这样的东西应该覆盖文件中的主机名值吗?

java -jar abc.jar config.properties hostName=machineB.domain.host.com
  • 还有,有什么方法可以在运行abc.jar 的同时添加--help,这样可以告诉我们更多关于如何运行jar 文件以及每个属性的含义以及如何使用它们的信息?我在运行大多数 C++ 可执行文件或 Unix 东西时看到了 --help,所以不确定我们如何在 Java 中做同样的事情?

我是否需要在 Java 中为此使用 CommandLine 解析器来实现这两件事?

【问题讨论】:

  • 那是您使用传递给public static void main 方法的String[] args 变量的时候。
  • @LuiggiMendoza 感谢您的建议。你能提供一个例子,我将如何做到这一点?我还需要添加--help 功能,任何人都可以通过该功能了解如何运行这个 jar 以及各种配置参数是什么以及它们一般意味着什么?我们需要使用像 JCommander 这样的命令行解析器吗?
  • 您可以手动完成或使用类似的库。决定权取决于您(或您的团队)。

标签: java parsing command-line properties command-line-arguments


【解决方案1】:

如果您的命令行中仅有的内容是:hostName=machineB.domain.host.com 而不是任何其他类型的参数,那么您可以大大简化命令行处理:

首先,将所有命令行参数与换行符连接起来,就好像它们是一个新的配置文件一样:

StringBuilder sb = new StringBuilder();
for (String arg : args) {
    sb.append(arg).append("\n");
}
String commandlineProperties = sb.toString();

现在,您有两个属性来源,您的文件和这个字符串。您可以将它们都加载到单个 Properties 实例中,其中一个版本覆盖另一个版本:

if (...the config file exists...) {
    try (FileReader fromFile = new FileReader("config.properties")) {
        prop.load(fromFile);
    }
}

if (!commandlineProperties.isEmpty()) {
    // read, and overwrite, properties from the commandline...
    prop.load(new StringReader(commandlineProperties));
}

【讨论】:

  • 非常感谢 rolfl 的帮助。我的第二个问题呢?我将如何接近那个。有什么想法吗?
  • CommandLine 通常用于此目的。我(几年前)写了我自己的,我工作的公司拥有,所以我不能分享。在此处查看 Apache CLI:commons.apache.org/proper/commons-cli
猜你喜欢
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2013-03-30
  • 2021-06-26
  • 1970-01-01
  • 2015-01-25
  • 2012-12-02
  • 2016-01-26
相关资源
最近更新 更多