我看到了这个例子,我没有看到在InputStream
上调用close()
方法,那么prop.load()
会自动关闭流吗?还是这个例子中有bug ?
流在属性之后没有关闭。load ()
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());
}
上面的代码返回"-1",因此流没有关闭。否则它应该抛出java.io.IOException: Stream Closed
为什么要问Properties.load(InputStream inStream)
的javadoc什么时候这么说?
在此方法返回后,指定的流保持打开。
从Java 6开始就一直这么说。
正如EJP在评论中所说:不要依赖任意的网络垃圾。使用官方Oracle Java文档作为您的主要信息来源。
下面的try-with-resources将自动关闭InputStream
(如果需要,您可以添加catch
和finally
):
try (InputStream is = new FileInputStream("properties.txt")) {
// is will be closed automatically
}
在try块开头声明的任何资源都将被关闭。因此,新的构造使您不必将try块与专用于适当资源管理的相应finally块配对。
Oracle的文章:http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html