Property.properties
sample.user = "sampleUser"
sample.age = "sampleAge"
sample.location = "sampleLocation"
我可以通过 prop.getProperty("sample.user") 从属性文件中获取属性值。
我想知道以下情况是否可行:
prop.getProperty("sample.*");
结果:
示例用户
样本年龄
示例位置
任何人都可以建议是否有任何方法可以从属性文件中获取上述结果吗?
一种解决方案是获取整个属性文件并循环访问它。 但是我的财产文件很长,我认为这会导致性能问题,因为我需要经常调用它。
Anther 将使用.xml文件而不是 .properties 文件。
Properties
对象(对象形式的.properties
文件)只是一个Hashtable<Object,Object>
(和一个Map
)。不适合2016年的任何用途,但完全可行。
提取匹配项并不是特别低效,即使是 000 行也应该在微不足道的时间内返回(可能只有几毫秒)。这完全取决于您需要检查的频率。如果您只需要它们一次,只需缓存生成的matchingValues
并重新引用它。
不,你不能直接prop.getProperty("sample.*");
,但代码通过Map
接口非常简单:
Properties p = new Properties();
p.setProperty("sample.user", "sampleUser");
p.setProperty("sample.age", "sampleAge");
p.setProperty("sample.location", "sampleLocation");
Pattern patt = Pattern.compile("sample.*");
final List<String> matchingValues = new ArrayList<>();
for (Entry<Object,Object> each : p.entrySet()) {
final Matcher m = patt.matcher((String) each.getKey());
if (m.find()) {
matchingValues.add((String) each.getValue() );
}
}
System.out.println(matchingValues);
上述匹配和构建在我 5 岁的 iMac 上花费了 0.16 毫秒。
切换到 XML 表示形式会更复杂,加载和处理速度肯定更慢。
在Java 8中,它可能看起来像
Properties p = new Properties();
...
List<String> matchingValues = p.entrySet().stream()
.filter(e -> e.getKey().toString().matches("sample.*"))
.map(e -> e.getValue().toString())
.collect(Collectors.toList());
System.out.println(matchingValues);