【JAVAベース】-IOストリームクローズ

1826 ワード

Java 7では、ストリームをオフにします。自分で書く必要はありません。
実現した自動クローズインターフェースの種類はすべてtry構造体で定義できます。javaは自動的にオフしてくれます。異常が発生した場合もすぐにできます。try構造体で複数定義できます。セミコロンで仕切ればいいです。
try (OutputStream out = new FileOutputStream("");OutputStream out2 = new FileOutputStream("")){  
    // ...       
} catch (Exception e) {  
    throw e;  
}  
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();  
    }  
}
複数のストリームを閉じるときは、面倒なのですべてのストリームのコードを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();  
    }  
}
ループ中にストリームを作成し、ループ外でオフします。最後のストリームがオフになります。
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();  
        }  
    }  
}