如何通过命令行参数覆盖属性文件值?

joh*_*ohn 6 java command-line parsing properties command-line-arguments

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

hostName=machineA.domain.host.com
emailFrom=tester@host.com
emailTo=world@host.com
emailCc=hello@host.com
Run Code Online (Sandbox Code Playgroud)

现在我正在从我的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

java -jar abc.jar config.properties
Run Code Online (Sandbox Code Playgroud)

我的问题是 -

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

这样的事情应该覆盖文件中的hostName值?

java -jar abc.jar config.properties hostName=machineB.domain.host.com
Run Code Online (Sandbox Code Playgroud)
  • 而且,有没有办法添加--help在运行abc.jar,可以进一步了解如何运行jar文件的,哪些是每个属性的含义以及如何使用它们告诉我们什么?我--help在运行大部分C++可执行文件或Unix时看到过,所以不确定我们如何在Java中做同样的事情?

我是否需要在Java中使用CommandLine解析器来实现这两个目标?

rol*_*lfl 2

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

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

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

现在,您有两个属性源:您的文件和该字符串。您可以将它们加载到单个 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));
}
Run Code Online (Sandbox Code Playgroud)