【问题标题】:What should I do with FileOutputStream after deleting File删除 File 后 FileOutputStream 该怎么办
【发布时间】:2020-09-28 03:44:49
【问题描述】:

我正在使用 Spring Boot 开发一种将多个 .pfd 文件连接成一个并返回其字节数组的方法:

public byte[] concatDocs() {
    List<Doc> documents = getAllDocs();

    PDFMergerUtility ut = new PDFMergerUtility();

    String nameOfTemporaryFile = "temporaryFile.pdf";

    File file = new File(nameOfTemporaryFile);

    FileOutputStream out = null;

    try {
        out = new FileOutputStream(file);

        for (Doc doc : documents) {
            InputStream is = new ByteArrayInputStream(doc.getFile());
            ut.addSource(is);
        }

        ut.setDestinationStream(out);
        ut.mergeDocuments(null);

        byte[] fileBytes = Files.readAllBytes(file.toPath());

        file.delete();

        return fileBytes;
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

代码本身运行良好:它获取Doc 列表,创建临时File 以及FileOutputStream(来自java.io),使用PDFMergerUtility 合并文件并生成字节数组,最后从计算机中删除文件。我的问题是:

我在互联网上看到的每个与 I/O 流一起使用的代码最后总是会关闭它们(使用 stream.close()),但我从来没有找到一个很好的解释来解释为什么它们总是这样做......
我应该在readAllBytes 之前关闭out 吗?
我应该在删除文件之前还是之后关闭out
当我删除文件时,我什至需要关闭out吗?
如果抛出异常怎么办?我应该在 finally 子句上关闭 out 吗?
我应该在某个地方out.flush() 吗?
我应该打电话给System.gc();吗?

提前致谢。

【问题讨论】:

  • 这个问题和你的类似。 stackoverflow.com/questions/26541513/…
  • 您需要在删除文件之前关闭它。否则删除可能无效。但是如果你要将它全部加载到内存中,为什么不使用 ByteArrayOutputStream 来代替呢?

标签: java spring-boot file-io


【解决方案1】:

始终最好关闭资源以避免任何数据泄漏。 在Java-7 中,我们提供了资源功能的试用功能,您可以使用它。 try-with-resources – 允许我们声明要在 try 块中使用的资源,并确保在执行该块后资源将被关闭。 您可以在此处找到更多相关信息
https://mkyong.com/java/try-with-resources-example-in-jdk-7/
https://www.baeldung.com/java-try-with-resources

【讨论】:

    【解决方案2】:

    从 java 7 开始,他们引入了 try with resource(你可以在 oracle 文档中看到)。它可以帮助减少手动关闭流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2021-10-15
      • 2013-12-17
      • 2016-09-30
      • 1970-01-01
      • 2012-06-06
      • 2019-12-20
      • 2019-06-01
      相关资源
      最近更新 更多