下面是一個例子,我有關於問題(它來自另一個SO問題):關閉流/插座的try-catch-終於
public static void writeToFile (final String filename)
{
PrintWriter out = null;
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filename);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos, "UTF-8")));
for (final String line : log)
{
out.println(line);
}
out.flush();
out.close();
}
catch (final Exception e)
{
System.err.println("Unable to write log to file.");
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (final IOException e)
{
System.err.println("Unable to write log to file.");
}
}
}
}
現在我覺得這個代碼工作正常,並釋放所有的資源,其中應該等我的問題是:
我爲什麼要在
try-catch-finally
的finally
部分被關閉FileOutputStream
?當然,我可以在try-catch
之後連續輸入代碼?爲什麼我必須單獨關閉
FileOutputStream
而不是簡單地用new OutputStreamWriter(fos, ...
替換new OutputStreamWriter(new FileOutputStream(filename), ...
?如果我先關閉FileOutputStream,是否會自動關閉剩餘部分並釋放資源?同樣的問題適用於套接字,如果關閉套接字連接,會自動關閉流讀寫器並釋放資源?由於不同的系統具有不同的字符集(或沿着這些行),我已經多次被告知要確保我讀寫具有「UTF-8」的流。這是否適用於讀取/寫入RAW字節數據(比如來自非文本文件或加密的結果),因爲我認爲字符集只能處理文本字符?
move code'out.close();' for out = new PrintWriter(...)最終阻止,與'fos = new FileOutputStream(filename)'的定義相同;'' – mKorbel 2011-05-17 14:59:27
你寫道:「我目前找不到線程」。也許你的意思是22answers.com上的[「何時使用Java中的哪個Writer子類;常見實踐」](http://www.22answers.com/posts/answers/en/4069698)。 – 2011-05-17 15:05:34
@mKorbel - 謝謝。 @Marnix Klooster - 是的,它實際上是SO上的一篇文章的副本。 @Jonathon - 感謝編輯。 – Cheetah 2011-05-17 20:20:11