【发布时间】:2016-01-21 10:13:03
【问题描述】:
我正在用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
【问题讨论】:
-
您能否详细说明并举例说明您希望如何使用它?通过 cmd 在 java 内部和外部获取参数有什么区别?
标签: java command-line-interface properties-file