Java如何从文件和cli中读取参数?

标签 java command-line-interface properties-file

我正在用java编写一个工具,我需要提供一些用户可以设置的参数。

我认为能够将所有参数保存在文件中(并且只需运行 .jar)并通过命令行更改保存的参数是很好的。

因此,我需要以某种方式处理来自两个来源的参数(优先级、有效性等)。目前,我使用 Apache.commons.cli 读取 cli 提供的参数,并使用 java.util.Properties 读取文件提供的属性。然后我将这些属性组合在一起(并根据需要添加一些默认值)。但我不喜欢这个结果,它对我来说似乎过于复杂。

所以代码是这样的:

Properties fromFile = new Properties();
fromFile.load(new FileInputStream("settings.properties"));
cli.Options cliOptions = new cli.Options();
cliOptions.addOption(longName, shortName, hasArg, description);
//add more options
Parser parser = new DefaultParser();
CommandLine fromCli = parser.parse(cliOptions, args);
//at this point I have two different objects with properties I need,
//and I need to get every property from fromCli, check it's not empty,
// if it is, get it from fromFile, etc

所以问题是:是否有任何库可以处理来自不同来源(cli、文件、默认值)的属性?我尝试谷歌搜索,但没有成功。抱歉,如果我的谷歌搜索能力还不够。

我希望代码是这样的:

import org.supertools.allPropsLib;
allPropsLib.PropsHandler handler = new allPropsLib.PropsHandler();
handler.addOptions(name, shortName, hasArg, description, defaultsTo);
handler.addSource(allPropsLib.Sources.CLI);
handler.addSource(allPropsLib.Sources.FILE);
handler.addSource(allPropsLib.Sources.DEFAULTS);
handler.setFileSource("filename");
allPropsLib.PropsContainer properties = handler.readAllProps();
// and at this point container should contain properties combined
// maybe there should be some handler function to tell the priorities,
// but I don't need to decide from where each properties should be taken

最佳答案

定义属性后,无论来源如何,都将它们加载到 java.util.Properties 容器中。然后调用逻辑并将容器作为参数传递给它。

关于Java如何从文件和cli中读取参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920827/

相关文章:

python - 将 click.MultiCommand 与类方法结合使用

java - 文本字段中没有显示任何内容

java - 使用 Java 库实现 pwinty API

Java泛型方法通配符不匹配问题

spring - 原始类型的属性不允许使用“lateinit”修饰符 - Kotlin

java - Spring中的动态@Value等价物?

java - 属性文件中保存的值是否有长度限制?

java - 如何使用java将日期和时间发送到SQL

azure cli获取单个blob(文件)大小列表

git - 是否可以在不打开浏览器的情况下从 CLI 在 GitHub 上创建远程仓库?