重用FileOutputStream时应该关闭流吗?

hackjutsu

如标题所述,重用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...");
}
5gon12eder

我认为此处的混乱围绕“重新使用”概念展开FileOutputStream您所做的只是通过将新值与标识符outfile相关联来重复使用标识符变量的名称)。但这对Java编译器仅具有语法意义。名称-所指对象FileOutputStream只是掉落在地板上,最终将在以后未指定的时间点被垃圾收集。曾经引用它的变量如何处理都没有关系。无论您将其重新分配FileOutputStream,设置为null还是让它超出范围都是一样的。

close显式调用将所有缓冲的数据刷新到文件并释放关联的资源。(垃圾收集器也会释放它们,但您不知道何时会发生这种情况。)请注意,它close也可能会抛出一个,IOException因此,真正重要的是您知道尝试操作的点,只有在调用函数时才能这样做明确地。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章