有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

命令行界面Java如何从文件和cli读取参数?

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

我认为最好能够将所有参数保存在一个文件中(并且只运行.jar),并通过命令行修改保存的参数

因此,我需要以某种方式处理来自两个来源(优先级、有效性等)的参数。目前我使用Apache。平民cli读取cli提供的参数和java。util。文件提供的属性的属性。然后我将这些属性组合在一起(如果需要,还可以添加一些默认值)。但我不喜欢结果,我觉得太复杂了

代码是这样的:

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) 个答案

  1. # 1 楼答案

    定义属性后,将它们加载到java.util.Properties容器中,而不考虑其来源。然后调用逻辑并将其作为参数传递给容器