共計 736 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 關閉流的方法有以下幾種:
- 使用 try-finally 語句塊,在 finally 塊中關閉流。這是最常見的關閉流的方式,確保在程序執行完后,流一定會被關閉,避免資源泄漏。
InputStream is = null;
try {is = new FileInputStream("file.txt");
// 使用流進行讀取操作
} catch (IOException e) {e.printStackTrace();
} finally {if (is != null) {try {is.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
- 使用 try-with-resources 語句,在 try 塊中創建流對象,并在括號中聲明流對象,當 try 塊結束時,自動關閉流。
try (InputStream is = new FileInputStream("file.txt")) {// 使用流進行讀取操作
} catch (IOException e) {e.printStackTrace();
}
- 使用 try-with-resources 語句,同樣在括號中聲明流對象,但是可以聲明多個流對象,用分號隔開。
try (InputStream is = new FileInputStream("file.txt");
OutputStream os = new FileOutputStream("output.txt")) {// 使用流進行讀寫操作
} catch (IOException e) {e.printStackTrace();
}
在 Java 7 及以上版本中,推薦使用 try-with-resources 語句來關閉流,它簡化了代碼,并且可以確保流一定會被關閉,避免了忘記關閉流的問題。
丸趣 TV 網 – 提供最優質的資源集合!
正文完