【问题标题】:The Properties.load would close the InputStream?Properties.load 会关闭 InputStream 吗?
【发布时间】:2017-02-25 22:48:47
【问题描述】:

我看到this example,并没有看到InputStream上调用的close()方法,那么prop.load()会自动关闭流吗?还是示例中有错误?

【问题讨论】:

  • 我刚刚检查了 java 代码的 load(stream) 并没有关闭流。
  • 示例中的错误。 Properties.load() 不会关闭流。你必须这样做。质量很差的例子。它甚至不适用于某些操作系统。不要依赖任意的互联网垃圾。使用 Oracle Java 教程。

标签: java properties inputstream java-io


【解决方案1】:

如果您使用的是 Java 7 或更高版本,则可以使用 try-with-resources。 Oracle 的文章在这里:http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html

在 try 块打开中声明的任何资源都将被关闭。因此,新构造使您不必将 try 块与专用于适当资源管理的相应 finally 块配对。

下面会自动关闭InputStream(如果需要,可以添加catchfinally):

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

【讨论】:

    【解决方案2】:

    Properties.load(InputStream inStream) 的 javadoc 这么说的时候为什么要问?

    此方法返回后,指定的流保持打开状态

    从 Java 6 开始就一直这么说。

    正如 EJP 在comment 中所说:不要依赖任意 Internet 垃圾。使用官方 Oracle Java 文档作为您的主要信息来源。

    【讨论】:

      【解决方案3】:

      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());
      }
      

      上面的代码返回“-1”,所以流没有关闭。否则它应该抛出java.io.IOException: Stream Closed

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 2012-03-21
        • 2016-04-05
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        • 2011-08-12
        相关资源
        最近更新 更多