使用输入流从 XML 文件中读取属性?

Reading properties from an XML file using Input Stream?

目前在我的 Java 应用程序中,我使用以下 Class 来从我的 properties 文件 (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);
    }
}

使用 MyProperties class 实例化 int 的示例:

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

我想更改此 class 以便读取 XML 属性文件而不是例如application.Properties。

我怎样才能做到这一点,并且仍然能够使用 MyProperties class 实例化值?

阅读 javadoc Properties.loadFromXML(...) 方法。

方法总结:

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

Properties javadoc 包含 XML 文档(文件)的 DTD。


最好使用这样的 try-with-resources 编写加载程序:

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

此外,像这样捕获和压缩异常是个坏主意。

  1. 不抓Exception.
  2. 如果属性加载失败,您很可能希望应用程序 "bail out"。

最后,您可能不应该在静态初始值设定项中加载属性,因为这使您没有干净的方法来处理可能出现的任何异常。