有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在重用FileOutputStream时应该关闭流吗?

正如标题中所述,在重用FileOutputStream变量时是否应该关闭流?例如,在以下代码中,我应该在为outfile.close()分配新文件之前调用它吗?为什么

谢谢:)

FileOutputStream outfile = null;
int index = 1;

while (true) {

    // check whether we should create a new file
    boolean createNewFile = shouldCreateNewFile();

    //write to a new file if pattern is identified
    if (createNewFile) {
        /* Should I close the outfile each time I create a new file?
        if (outfile != null) {
            outfile.close();
        }
        */
        outfile = new FileOutputStream(String.valueOf(index++) + ".txt");
    }

    if (outfile != null) {
        outfile.write(getNewFileContent());
    }

    if (shouldEnd()) {
        break;
    }
}

try {
    if (outfile != null) {
        outfile.close();
    }
} catch (IOException e) {
    System.err.println("Something wrong happens...");
}

共 (3) 个答案

  1. # 1 楼答案

    我认为这里的困惑围绕着“重复使用”这个FileOutputStream的概念。您所做的只是通过将一个新值与之关联,重新使用一个标识符(变量的名称^{)。但这对Java编译器来说只有语法意义。名为FileOutputStream对象被简单地扔在地板上,最终会在未指定的时间点被垃圾收集。对曾经引用它的变量做什么并不重要。无论您是将其重新分配给另一个FileOutputStream,将其设置为null,还是让其超出范围,都是一样的

    调用close显式地将所有缓冲数据刷新到文件中,并释放相关资源。(垃圾收集器也会释放它们,但你不知道什么时候会发生这种情况。)请注意close也可能抛出一个IOException,因此知道尝试操作的时间点非常重要,只有显式调用该函数时才能执行该操作

  2. # 2 楼答案

    是的一旦处理完一个文件(流),就应该关闭它。因此,与文件(流)一起分配的资源将被释放到操作系统,如文件描述符、缓冲区等

    Java文档FileOutputStream.close()

    Closes this file output stream and releases any system resources associated with this stream. This file output stream may no longer be used for writing bytes.

    未关闭的文件描述符甚至可能导致java程序中的资源泄漏Reference

  3. # 3 楼答案

    即使没有自动资源管理或try-with-resources(见下文),您的代码也可以变得更加可读和可靠:

    for (int index = 1; shouldCreateNewFile(); ++index) {
      FileOutputStream outfile = new FileOutputStream(index + ".txt");
      try {
        outfile.write(getNewFileContent());
      }
      finally {
        outfile.close();
      }
    }
    

    然而,Java7为闭包引入了一种新的语法,这种语法在出现错误时更可靠,信息更丰富。使用它,您的代码将如下所示:

    for (int index = 1; shouldCreateNewFile(); ++index) {
      try (FileOutputStream outfile = new FileOutputStream(index + ".txt")) {
        outfile.write(getNewFileContent());
      }
    }
    

    输出流仍将被关闭,但如果try块内部存在异常,并且在关闭流时出现另一个异常,则该异常将被抑制(链接到主异常),而不是像前面的示例那样导致主异常被丢弃

    在Java7或更高版本中,应该始终使用自动资源管理