【问题标题】:If I close ObjectOuputStream, then do not need to close FileOutputStream?如果我关闭了ObjectOutputStream,那么是否需要关闭FileOutputStream?
【发布时间】:2014-02-26 21:15:59
【问题描述】:

我的代码如下。

Map<String, String> aMap = new HashMap();
aMap.put("A", "a");
FileOutputStream fos = new FileOutputStream(new File("some.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.write(aMap);
oos.flush();
oos.close();

我以为我需要关闭 fos,但其他人说没问题。 不关闭FileOutputStream真的好吗,因为我已经关闭了内部OutputStream?

【问题讨论】:

    标签: java memory file-io fileoutputstream objectoutputstream


    【解决方案1】:

    是的,您不需要单独关闭它。如果您关闭oos,它也会在内部关闭fos。关闭最外面的流将一直委托它

    【讨论】:

      【解决方案2】:

      No 你不需要关闭 FileOutputStream。 如果您检查close() 的代码,您会发现它关闭了输出流。

      请参阅文档http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html

      【讨论】:

      • 实际上,它甚至在 OutputStream 的文档中都有说明,因此对于任何表现良好的 OutputStream 都可以预期。 Quote:关闭此输出流并释放与此流相关的所有系统资源。
      【解决方案3】:

      您无需明确执行此操作,它会自动完成。看看 javadoc 中的例子:

      FileOutputStream fos = new FileOutputStream("t.tmp");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
      
        oos.writeInt(12345);
        oos.writeObject("Today");
        oos.writeObject(new Date());
      
        oos.close();
      

      链接可以在这里找到:Class ObjectOutputStream

      【讨论】:

        【解决方案4】:

        这是 Java 中的一般规则:如果您有多个链式/嵌套流,请说
        outStream3(outStream2(outStream1))(我只是用伪代码编写)您
        通常只需要关闭最外层的流 - 在这种情况下是outStream3
        在内部,当您在 outStream3 上调用 close 时,它​​会在 outStream2 上调用 close
        这将在outStream1 上调用close。此规则有一些例外,但
        这是你能记住的一般规则。

        【讨论】:

          猜你喜欢
          • 2018-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-15
          • 1970-01-01
          • 2021-04-05
          相关资源
          最近更新 更多