简体   繁体   中英

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"

I can get a property value from a property file by prop.getProperty("sample.user").

I was wondering if below case is possible:

prop.getProperty("sample.*");

Result:
sampleUser
sampleAge
sampleLocation

Can anybody please suggest if there is any way to get the above result from the property file?

One solution would be to get whole property file and iterate through it. But my property file is very long and I think it would cause performance issues as I need to call it very often.

Anther would ve use .xml file instead of .properties file.

A Properties object (a .properties file in object form) is just a Hashtable<Object,Object> (and a Map ). Not ideal for any use in 2016, but perfectly workable.

Extracting the matches isn't especially inefficient, and even 000s of lines should return in a trivial amount of time (potentially just a few milliseconds). It all depends how often you need to check. If you only need them once, just cache the resulting matchingValues and refer back to it.

No, you can't do prop.getProperty("sample.*"); directly, but the code is very straightforward via the Map interface:

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

The above matching and building took 0.16 millisecs on my 5-year-old iMac.

Switching to XML representation would be more complicated and definitely slower to load and process.

In Java 8 it may looks like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM