【发布时间】:2012-08-15 00:23:55
【问题描述】:
getResourceAsStream() 是java.lang.Class 类的方法。此方法在类路径中找到具有给定名称的资源。实际上这个方法委托给这个对象的类加载器。在此示例中,PropUtil 对象的类加载器。但在委托之前,使用以下算法从给定的资源名称构造一个绝对资源名称。
【问题讨论】:
-
...嗯?您刚刚回答了自己的问题吗?
标签: java
getResourceAsStream() 是java.lang.Class 类的方法。此方法在类路径中找到具有给定名称的资源。实际上这个方法委托给这个对象的类加载器。在此示例中,PropUtil 对象的类加载器。但在委托之前,使用以下算法从给定的资源名称构造一个绝对资源名称。
【问题讨论】:
标签: java
如果您使用静态方法并从类路径文件夹加载属性文件,则可以使用以下代码:
//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
【讨论】:
getResourceAsStream打开的InputStream加载后需要关闭吗?
Properties.load() javadoc 声明“此方法返回后指定的流保持打开状态。”
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
【讨论】:
getResourceAsStream打开的InputStream加载后需要关闭吗?
Properties.load() javadoc 声明“此方法返回后指定的流保持打开状态。”