【问题标题】:Reading properties from an XML file using Input Stream?使用输入流从 XML 文件中读取属性?
【发布时间】:2016-04-19 11:47:58
【问题描述】:

目前在我的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 类实例化int 的示例:

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

我想更改此类以读取XML 属性文件,而不是例如应用程序。属性。

我怎样才能做到这一点,并且仍然保持使用 MyProperties 类实例化值的能力?

【问题讨论】:

标签: java xml properties static inputstream


【解决方案1】:

阅读javadoc 以了解Properties.loadFromXML(...) 方法。

方法总结:

将指定输入流上的 XML 文档表示的所有属性加载到此属性表中。

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. 如果无法加载属性,您很可能希望应用程序“退出”。

最后,您可能不应该在静态初始化程序中加载属性,因为这会让您无法处理任何可能出现的异常。

【讨论】:

    猜你喜欢
    • 2015-01-14
    • 2013-07-16
    • 2020-11-11
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多