[英]Should I close stream when reusing 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...");
}
是。 完成一個文件(流)后,應始終關閉它。 這樣與文件(流)一起分配的資源將被釋放到操作系統,如文件描述符,緩沖區等。
Java文檔FileOutputStream.close()
關閉此文件輸出流並釋放與此流關聯的所有系統資源。 此文件輸出流可能不再用於寫入字節。
未封閉的文件描述符甚至可能導致java程序中的資源泄漏。 參考
我認為這里的混亂圍繞着“重用” FileOutputStream
的概念。 你在做什么是簡單地重新使用的標識符 (名稱outfile
通過關聯與它新的價值的變量)。 但這只對Java編譯器有語法意義。 名稱引用的對象 - FileOutputStream
- 只是放在地板上,最終將在未指定的時間點進行垃圾收集。 使用曾經引用它的變量做什么並不重要。 無論是重新分配另一個FileOutputStream
,將其設置為null
還是讓它超出范圍都是一樣的。
調用close
顯式刷新所有緩沖數據到文件並釋放相關資源。 (垃圾收集器也會釋放它們,但是你不知道什么時候會發生這種情況。)注意close
也可能拋出一個IOException
所以你知道嘗試操作的點非常重要,只有你調用它才能執行明確的功能。
即使沒有自動資源管理或資源試用 (見下文),您的代碼也可以更加可讀和可靠:
for (int index = 1; shouldCreateNewFile(); ++index) {
FileOutputStream outfile = new FileOutputStream(index + ".txt");
try {
outfile.write(getNewFileContent());
}
finally {
outfile.close();
}
}
但是,Java 7為閉包引入了一種新語法,在出現錯誤時更加可靠且信息豐富。 使用它,您的代碼將如下所示:
for (int index = 1; shouldCreateNewFile(); ++index) {
try (FileOutputStream outfile = new FileOutputStream(index + ".txt")) {
outfile.write(getNewFileContent());
}
}
輸出流仍將關閉,但如果try
塊內有異常,而另一個異常關閉流,則異常將被抑制(鏈接到主異常),而不是導致主異常被丟棄,如上一個例子。
您應始終在Java 7或更高版本中使用自動資源管理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.