2015-10-14 21 views
4

正如標題所述,我應該在重新使用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..."); 
} 
+1

*「在爲其分配新文件之前」* - 是的,您可以將更改保留在緩衝區中,這意味着它們可能不會保存到文件中。您正在使用文件句柄,這是操作系統中有限的資源。您正在JVM中佔用資源。你應該隨時清理你自己。查看[The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)以獲取更好的解決方案,以處理可關閉的資源 – MadProgrammer

回答

1

我認爲這裏的困惑圍繞着「重新使用」FileOutputStream的概念。你正在做的只是重新使用標識符(名稱outfile變量)通過關聯一個新值與它。但是這隻對Java編譯器具有語法意義。名爲FileOutputStream對象只是簡單地放在地板上,最終將在未指定的時間點進行垃圾回收。不管你用這個曾經提到它的變量做什麼都沒有關係。無論你重新分配它FileOutputStream,將其設置爲null或讓它超出範圍都是一樣的。

調用close明確地將所有緩衝的數據刷新到文件並釋放關聯的資源。 (垃圾收集器也會釋放它們,但是你不知道什麼時候會發生這種情況。)請注意,close也可能會拋出一個IOException,所以確實很重要,因爲您知道嘗試操作的位置,只有在您致電該功能明確。

5

YES。一旦你完成了一個文件(流),你應該總是關閉它。因此,與該文件(流)分配的資源將被釋放給操作系統,如文件描述符,緩衝等

Java文檔FileOutputStream.close()

關閉此文件輸出流並釋放與關聯的系統資源這個流。該文件輸出流可能不再用於寫入字節。

未封閉的文件描述符甚至可能導致java程序中的資源泄漏。 Reference

2

即使沒有自動資源管理,或try-with-resources(見下文),你的代碼可以進行更可讀,可靠:

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或更高版本中使用自動資源管理。

相關問題