【Java】 File の Close処理について ~try-with-resources~

■ try-with-resources

 * C#の using のように、close()をしなくても自動的にclose処理をしてくれる
 * Java 1.7から使用可能

■ closeが一つの場合

構文

try (XxxxxStream stream = new XxxxxStream()) {
   // something
} catch (Exception ex) {
}

サンプル

一部抜粋
protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
   try (OutputStream outputStream = response.getOutputStream()) {
      response.setContentType("text/html;charset=utf-8");  
      outputStream.write("File not found".getBytes()); 
   } catch (Exception ex) {  
      ex.printStackTrace();
   }
}

■ closeが複数の場合

構文

try (XxxxxStream stream1 = new XxxxxStream();
     XxxxxStream stream2 = new XxxxxStream();
     XxxxxStream stream3 = new XxxxxStream()) {
   // something
} catch (Exception ex) {
}

サンプル

一部抜粋
private void download(HttpServletRequest request,
         HttpServletResponse response,
         File downloadFile) {
    
     try (OutputStream outputStream = response.getOutputStream();
           FileInputStream fileInputStream = new FileInputStream(downloadFile);
           BufferedInputStream bufferedInputStream =
                 new BufferedInputStream(fileInputStream);) {
         // something
     } catch (Exception ex) {
        ex.printStackTrace();
     }  
}

インターフェイス「AutoCloseable」

 * 自作のクラスでClose処理を入れたい場合に、使用する。

public class SampleClass implements AutoCloseable {
   // ...
}

API仕様

http://docs.oracle.com/javase/jp/7/api/java/lang/AutoCloseable.html


関連記事

実際にサンプル内で使用している
http://blogs.yahoo.co.jp/dk521123/33641421.html