陷阱 - 關閉它時不檢查 IO 流是否甚至未初始化
為防止記憶體洩漏,不應忘記關閉作業完成的輸入流或輸出流。這通常是使用 try
-catch
-finally
語句完成的,沒有 catch
部分:
void writeNullBytesToAFile(int count, String filename) throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
for(; count > 0; count--)
out.write(0);
} finally {
out.close();
}
}
雖然上面的程式碼可能看起來很無辜,但它有一個缺陷,可能使除錯無法進行。如果 out
初始化的行(out = new FileOutputStream(filename)
)丟擲一個異常,那麼當執行 out.close()
時 out
將是 null
,導致一個討厭的 NullPointerException
!
要防止這種情況,請在嘗試關閉之前確保該流不是 null
。
void writeNullBytesToAFile(int count, String filename) throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
for(; count > 0; count--)
out.write(0);
} finally {
if (out != null)
out.close();
}
}
更好的方法是使用資源,因為它會自動關閉流,概率為 0,無需使用 finally
塊即可丟擲 NPE。
void writeNullBytesToAFile(int count, String filename) throws IOException {
try (FileOutputStream out = new FileOutputStream(filename)) {
for(; count > 0; count--)
out.write(0);
}
}