正如标题所述,我应该在重新使用FileOutputStream变量时关闭流?例如,在下面的代码中,我应该在为其分配新文件之前调用outfile.close()
,为什么?重新使用FileOutputStream时应关闭流吗?
谢谢:)
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...");
}
*“在为其分配新文件之前”* - 是的,您可以将更改保留在缓冲区中,这意味着它们可能不会保存到文件中。您正在使用文件句柄,这是操作系统中有限的资源。您正在JVM中占用资源。你应该随时清理你自己。查看[The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)以获取更好的解决方案,以处理可关闭的资源 – MadProgrammer