【发布时间】:2015-03-04 22:55:39
【问题描述】:
我有一个像这样的属性文件 -
emailFrom=hello@abc.com
emailTo=world@abc.com
# can be separated by comma
whichServer=UserServer,GuestServer
maxTestInSec=120
numberOfUsers=1000
现在我正在用 Java 读取这样的属性文件,如果一切设置正确,它就可以工作 -
private static final Properties prop = new Properties();
private static String emailFrom;
private static String emailTo;
private static List<String> whichServer;
private static String maxTestInSec;
private static String numberOfUsers;
public static void main(String[] args) {
readConfig(args);
}
private void readConfig(String[] args) throws FileNotFoundException, IOException {
if (!TestUtils.isEmpty(args) && args.length != 0) {
prop.load(new FileInputStream(args[0]));
} else {
prop.load(TestTask.class.getClassLoader().getResourceAsStream("config.properties"));
}
emailFrom = prop.getProperty("emailFrom").trim();
emailTo = prop.getProperty("emailTo").trim();
whichServer = Arrays.asList(prop.getProperty("whichServer").trim().split(","));
maxTestInSec = prop.getProperty("maxTestInSec").trim();
numberOfUsers = prop.getProperty("numberOfUsers").trim();
}
问题陈述:-
我需要确保如果缺少任何属性值,那么我想为此使用默认值,如果该属性被注释掉,那么我也想使用默认值,但我会记录警告消息指出该属性丢失或为空,因此使用默认值。我正在尝试涵盖读取文件的所有极端情况-
- 现在假设,如果我没有在上述文件中为我的任何属性指定值,那么我想为我没有提供的属性使用默认值并记录为警告,指出没有值已为此属性提供,因此使用默认值。例如:假设我没有为
emailFrom字段提供任何值,那么我想使用默认值作为hello@abc.com和其他类似的东西。所有属性的默认值为:
emailFrom=hello@abc.com
emailTo=world@abc.com
whichServer=UserServer
maxTestInSec=30
numberOfUsers=500
- 此外,如果任何属性被注释掉,则上述代码将通过 NPE 异常。在那种情况下,我如何也可以使用默认值?
我应该开始为此使用命令行解析器吗?处理这些东西最好、最干净的方法是什么?
我不想有很多 if 块来添加检查然后设置默认值。
【问题讨论】:
标签: java file properties-file