how to read property name with spaces in java

Viewed 50454

I am trying to load all the property names present in the properties file using the below code:

for(Enumeration<String> en = (Enumeration<String>) prop.propertyNames();en.hasMoreElements();){

    String key = (String)en.nextElement();
    System.out.println("Property name is "+key);
}

But my properties file has the below contents:

username=
password=
Parent file name=
Child file name =

After running the code I am getting output as :

username password Parent Child

If the property name has spaces, it is only returning the first word..

Can any one please tell me how to do this?

4 Answers

This is how I do it:

public class PropHelper {
    final static String PROPERTY_FILEPATH = "blah/blah.properties";

    static String getPropertyWithSpaces(String property, String delimiter) {
        try {
            FileReader reader = new FileReader(PROPERTY_FILEPATH);
            Properties propertiesObj = new Properties();
            propertiesObj.load(reader);
            return propertiesObj.getProperty(property).replaceAll(delimiter, "");
        } catch (Exception ex) {
            System.out.println("FATAL ERROR: " + ex.getMessage());
            System.exit(1);
        }

        return null;
    }
}

Somewhere in .properties file:

settings = ` ⚙ Settings `

This is how I call it:

System.out.println("|" + PropHelper.getPropertyWithSpaces("settings", "`") + "|");

This method works with leading, internal and trailing spaces. Enjoy!

Related