简体   繁体   English

该Properties.load将关闭InputStream吗?

[英]The Properties.load would close the InputStream?

I saw this example , and I didn't see the close() method invoked on the InputStream , so would prop.load() close the stream automatically? 我看到了这个示例 ,但没有看到InputStream上调用的close()方法,所以prop.load()会自动关闭流吗? Or is there a bug in the example? 还是示例中有错误?

The Stream is not closed after Properties.load () 在Properties.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());
}

The above code returns "-1" so the stream is not closed. 上面的代码返回“ -1”,因此不会关闭流。 Otherwise it should have thrown java.io.IOException: Stream Closed 否则应该抛出java.io.IOException: Stream Closed

Why do you ask when the javadoc of Properties.load(InputStream inStream) says this? 为什么要问当Properties.load(InputStream inStream)的javadoc这样说的时候?

The specified stream remains open after this method returns. 此方法返回后,指定的流保持打开状态

It has been saying that since Java 6. 自Java 6以来一直在说。

As EJP said in a comment : Don't rely on arbitrary Internet junk. 正如EJP在评论中所说: 不要依赖任意的互联网垃圾。 Use the official Oracle Java documentation as your primary source of information. 使用正式的Oracle Java文档作为您的主要信息来源。

If you are on Java 7 or later, you can use try-with-resources . 如果您使用的是Java 7或更高版本,则可以使用try-with-resources Article by Oracle here: http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html . Oracle的文章位于: http : //www.oracle.com/technetwork/articles/java/trywithresources-401775.html

Any resource declared within a try block opening will be closed. 在try块打开内声明的任何资源都将关闭。 Hence, the new construct shields you from having to pair try blocks with corresponding finally blocks that are dedicated to proper resource management. 因此,新的构造使您不必将try块与专用于适当资源管理的相应的finally块配对。

The following will close the InputStream automatically (you can add catch and finally , if you need them): 以下代码将自动关闭InputStream(如果需要,可以添加catch最后添加):

try (InputStream is = new FileInputStream("properties.txt")) {
    // is will be closed automatically
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM