Properties.load 会关闭 InputStream 吗?
The Properties.load would close the InputStream?
我看到了this example,但没有看到close()
方法在InputStream
上被调用,所以prop.load()
会自动关闭流吗?还是示例中存在错误?
Properties.load()
后Stream没有关闭
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(new File("abc.properties"));
new Properties().load(in);
System.out.println(in.read());
}
上面的代码returns“-1”所以流没有关闭。否则它应该抛出 java.io.IOException: Stream Closed
Properties.load(InputStream inStream)
的 javadoc 说这个的时候为什么要问?
The specified stream remains open after this method returns.
从Java6.
开始就一直在说
正如 EJP 在 中所说:不要依赖任意的 Internet 垃圾。 使用官方 Oracle Java 文档作为您的主要来源信息。
下面的try-with-resources会自动关闭InputStream
(如果需要可以添加catch
和finally
):
try (InputStream is = new FileInputStream("properties.txt")) {
// is will be closed automatically
}
Any resource declared within a try block opening will be closed. Hence, the new construct shields you from having to pair try blocks with corresponding finally blocks that are dedicated to proper resource management.
此处为 Oracle 文章:http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html。
我看到了this example,但没有看到close()
方法在InputStream
上被调用,所以prop.load()
会自动关闭流吗?还是示例中存在错误?
Properties.load()
后Stream没有关闭public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(new File("abc.properties"));
new Properties().load(in);
System.out.println(in.read());
}
上面的代码returns“-1”所以流没有关闭。否则它应该抛出 java.io.IOException: Stream Closed
Properties.load(InputStream inStream)
的 javadoc 说这个的时候为什么要问?
The specified stream remains open after this method returns.
从Java6.
开始就一直在说正如 EJP 在
下面的try-with-resources会自动关闭InputStream
(如果需要可以添加catch
和finally
):
try (InputStream is = new FileInputStream("properties.txt")) {
// is will be closed automatically
}
Any resource declared within a try block opening will be closed. Hence, the new construct shields you from having to pair try blocks with corresponding finally blocks that are dedicated to proper resource management.
此处为 Oracle 文章:http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html。