1.在finally中關閉流;
OutputStream out = null; try { out = new FileOutputStream(""); // ...操作流代碼 } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } }
2.在關閉多個流時因為嫌麻煩將所有關流的代碼丟到一個try中
OutputStream out = null; OutputStream out2 = null; try { out = new FileOutputStream(""); out2 = new FileOutputStream(""); // ...操作流代碼 } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close();// 如果此處出現異常,則out2流也會被關閉 } } catch (Exception e) { e.printStackTrace(); } try { if (out2 != null) { out2.close(); } } catch (Exception e) { e.printStackTrace(); } }
3.在循環中創建流,在循環外關閉,導致關閉的是最后一個流
for (int i = 0; i < 10; i++) { OutputStream out = null; try { out = new FileOutputStream(""); // ...操作流代碼 } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } } }
4.在Java7中,關閉流這種繁瑣的操作就不用我們自己寫了
只要實現的自動關閉接口(Closeable)的類都可以在try結構體上定義,java會自動幫我們關閉,及時在發生異常的情況下也會。可以在try結構體上定義多個,用分號隔開即可,如:
try (OutputStream out = new FileOutputStream("");OutputStream out2 = new FileOutputStream("")){ // ...操作流代碼 } catch (Exception e) { throw e; }