簡體   English   中英

在java中使用property.getProperty(“sample。*”)從屬性文件中獲取所有屬性值

[英]getting all the property values from property file with property.getProperty(“sample.*”) in java

Property.properties

sample.user =“sampleUser”
sample.age =“sampleAge”
sample.location =“sampleLocation”

我可以通過prop.getProperty(“sample.user”)從屬性文件中獲取屬性值。

我想知道以下情況是否可能:

prop.getProperty("sample.*");

結果:
sampleUser
sampleAge
sampleLocation

任何人都可以建議是否有任何方法可以從屬性文件中獲得上述結果?

一種解決方案是獲取整個屬性文件並迭代它。 但我的屬性文件很長,我認為它會導致性能問題,因為我需要經常調用它。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM