【问题标题】:How to load property file from classpath? [closed]如何从类路径加载属性文件? [关闭]
【发布时间】:2012-08-15 00:23:55
【问题描述】:

getResourceAsStream()java.lang.Class 类的方法。此方法在类路径中找到具有给定名称的资源。实际上这个方法委托给这个对象的类加载器。在此示例中,PropUtil 对象的类加载器。但在委托之前,使用以下算法从给定的资源名称构造一个绝对资源名称。

【问题讨论】:

标签: java


【解决方案1】:

如果您使用静态方法并从类路径文件夹加载属性文件,则可以使用以下代码:

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

【讨论】:

  • getResourceAsStream打开的InputStream加载后需要关闭吗?
  • @CDT Properties.load() javadoc 声明“此方法返回后指定的流保持打开状态。
【解决方案2】:
final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

【讨论】:

  • getResourceAsStream打开的InputStream加载后需要关闭吗?
  • @CDT Properties.load() javadoc 声明“此方法返回后指定的流保持打开状态。
  • 这是 Java 7 引入的“使用资源尝试”语法。当 try {} 块退出时,流将自动关闭。在 Java 7 之前,您将在 finally {} 块中手动关闭此流。 docs.oracle.com/javase/tutorial/essential/exceptions/…
  • @DrewWills 是的,我们知道; cmets 是关于发布的未使用 Java 7 try-with-resources 构造 的原始代码
  • 根据我的经验,文件需要在类路径中找到前导“/”。
猜你喜欢
  • 1970-01-01
  • 2016-03-10
  • 2016-05-23
  • 2020-06-05
  • 2014-12-16
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多