JAvaにおけるtry-catchモジュールにおけるwith文ブロックの役割
以前try-catchを書いたとき、ストリームや接続などのオブジェクトに遭遇した場合、finally文を追加してオブジェクトを閉じる必要があります.今日、tryのwithモジュールはfinallyで手動で閉じる動作を省略することができ、withモジュールにこれらのオブジェクトを定義し、try文が完了した後、AutoCloseableまたはCloseableインタフェースを実現する必要がある場合、自動的にcloseオブジェクトをcloseすることができます.そして、この特性は実はjava 7に導入され、今ではjava 9になって、やっと発見されました.時代遅れですね!!!例えば、現在の書き方:
これで十分ですが、以前は複数のfinallyが必要で、オブジェクト定義はtryの前に置かなければなりません.
try (BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
これで十分ですが、以前は複数のfinallyが必要で、オブジェクト定義はtryの前に置かなければなりません.
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null!=bis){
bis.close();
}
if(null!=bos){
bos.close();
}
}