正如標題所述,我應該在重新使用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