我有一个像这样的属性文件 -
hostName=machineA.domain.host.com
emailFrom=tester@host.com
emailTo=world@host.com
emailCc=hello@host.com
现在我正在从我的 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();
}
}
大多数时候,我会通过命令行将上面的程序作为可运行的 jar 运行,就像这样 -
java -jar abc.jar config.properties
我的问题是-
- 有没有什么方法可以通过命令行覆盖属性文件中的上述属性,而无需在需要时触及文件?因为我不想在需要更改任何属性值时总是修改我的 config.properties 文件?这可能吗?
这样的东西应该覆盖文件中的主机名值吗?
java -jar abc.jar config.properties hostName=machineB.domain.host.com
- 还有,有什么方法可以在运行
abc.jar
时添加--help
,它可以告诉我们更多关于如何运行 jar 文件以及它的作用每个属性的含义以及如何使用它们?我在运行大多数 C++ 可执行文件或 Unix 时看到了--help
,所以不确定我们如何在 Java 中做同样的事情?
我是否需要在 Java 中为此使用命令行解析器来实现这两个目标?
最佳答案
如果您在命令行上只有这样的东西:hostName=machineB.domain.host.com
而不是任何其他类型的参数,那么您可以大大简化命令行处理很多:
首先,将所有命令行参数与换行符连接起来,就好像它们是一个新的配置文件一样:
StringBuilder sb = new StringBuilder();
for (String arg : args) {
sb.append(arg).append("\n");
}
String commandlineProperties = sb.toString();
现在,您有两个属性源,您的文件和这个字符串。您可以将它们都加载到一个 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));
}
关于java - 如何通过命令行参数覆盖属性文件值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27611136/