我有一个属性文件,其中存储服务器的名称和端口。这些值将在 Enum
中使用,以便能够在不接触代码的情况下更改这些值。
属性的内容如下所示:
PROD=FTPROD01:1122
问题是我必须拆分服务器和端口号,因为我使用这些值作为方法的参数:
server = properties.getProperty(this.name(), "").split(":")[0];
try {
port = Integer.valueOf(properties.getProperty(this.name(), "").split(":")[1]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("error");
}
如您所见,我捕获了ArrayIndexOutOfBoundsException
,这是一个运行时异常,以便检测第二个值是否丢失,因为如果属性文件“损坏”,程序将崩溃”。
这是获取多个值的好方法,还是有其他更优雅的方法?
最佳答案
Is this a good way to do get multiple values, or are there any other approaches, which are more elegant?
当然 - 不要尝试访问无效长度的数组 - 在执行其他操作之前检测它。
String[] bits = properties.getProperty(this.name(), "").split(":");
if (bits.length == 2) {
server = bits[0];
port = Integer.valueOf(bits[1]);
} else {
// Log the corruption or whatever...
}
请注意,如果 valueOf
抛出 NumberFormatException
,这仍然可能失败。
基本上,您应该避免捕获异常,您可以避免一开始就引发异常。
关于java.util.Properties 多个值 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13415153/