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

时间:2016-01-21 10:13:03

标签: 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

1 个答案:

答案 0 :(得分:1)

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