Question

I am using one .properties file. In that I have following config parameters :

Appnameweb = app1
Appnamemobile = app2
Appnameweb1 = app3

There can be many config param starting with Appname provided by user. How to read all properties file parameters in which key will contain particular String like in this case Appname?

Was it helpful?

Solution

Generally take a look on javadoc of java.util.Properties. To make you life easier I will give you this code snippet that can help you to start:

Properties props = new Properties();
props.load(new FileInputStream("myfile.properties"));
for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) {
    String name = (String)e.nextElement();
    String value = props.getProperty(name);
    // now you have name and value
    if (name.startsWith("Appname")) {
        // this is the app name. Write yor code here
    }
}

OTHER TIPS

Properties props = new Properties();
props.load(new FileInputStream("file.properties"));
Enumeration<String> e = props.getNames();
List<String> values = new ArrayList<String>();
while(e.hasMoreElements()) {
    String param = (String) e.nextElement();
    if(param != null && param.contains("Appname")) { 
         values.add(props.getProperty(param));
    }   
}

If you're using java Properties, then you can do something on the lines of this.

  1. Get the Set<Object> of keys using the Properties#keySet() method.
  2. Start a for loop and for each object in the key set, convert the Object to String either by a cast or using the toString() method.
  3. With the converted String, check if it contains the common string "Appname" using the String#contains() or String#startsWith()method depending on your needs.
  4. If it does, get the value for that key using the Properties#getProperty() method and do whatever you want with the value.
Properties prop = new Properties();
    try {
        prop.load(this.getClass().getClassLoader().getResourceAsStream("filename.properties"));
        Set<Object> set = prop.keySet();

        for(Object obj : set){
            String str = obj.toString();
            if(str.startsWith("Appname")) {
                //System.out.println("");
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top