我有一个像这样的属性文件-
hostName=machineA.domain.host.com
[email protected]
[email protected]
[email protected]
现在,我正在从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
我的问题是-
这样的事情应该覆盖文件中的hostName值吗?
java -jar abc.jar config.properties hostName=machineB.domain.host.com
--help
在运行时是否有任何添加方法abc.jar
可以告诉我们更多有关如何运行jar文件以及每个属性意味着什么以及如何使用它们的信息?我已经--help
在运行大多数C ++可执行文件或Unix东西时看到了,所以不确定是否可以在Java中做同样的事情?我是否需要在Java中使用CommandLine解析器来实现这两个目标?
如果命令行上仅有的东西是::,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));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句