简体   繁体   中英

Reading properties from an XML file using Input Stream?

Currently within my Java Application I have the following Class that I use in order to retrieve values from my properties file (application.properties):

public class MyProperties {
    private static Properties defaultProps = new Properties();
    static {
        try {

            java.io.InputStream in= MyProperties.class.getClassLoader().getResourceAsStream("application.properties");
            defaultProps.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String getProperty(String key) {
        return defaultProps.getProperty(key);
    }
}

An example of instantiating an int using the MyProperties class:

int maxNumberOfPeople = Integer.parseInt(MyProperties.getProperty("maximumPeople"));

I would like to change this class in order to read an XML properties file rather than eg application.Properties.

How can I do so, and still keep the ability to still instantiate values using the MyProperties class?

Read the javadoc for the Properties.loadFromXML(...) method.

Method summary:

Loads all of the properties represented by the XML document on the specified input stream into this properties table.

The Properties javadoc includes the DTD for the XML document (file).


It would be better to write your loader using a try-with-resources like this:

try (java.io.InputStream in = MyProperties.class.getClassLoader().
            getResourceAsStream("application.properties")) {
    // load properties
} catch (Exception e) {
    e.printStackTrace();
}

Also, it is a bad idea to catch and squash exceptions like that.

  1. Don't catch Exception .
  2. If the properties failed to load, you most likely want the application to "bail out".

Finally, you probably shouldn't load the properties in a static initializer, because that leaves you with no clean way to deal with any exceptions that might arise.

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