LoginSignup
49
48

More than 5 years have passed since last update.

Java7のtry-with-resources構文でcloseし忘れを防ぐ

Posted at

Java7のtry-with-resources構文でcloseし忘れを防ぐ

DBやらfileやらにアクセスする際に


        FileInputStream is = null;
        FileOutputStream os = null;
        try{
            is = new FileInputStream("hoge.txt");
            InputStreamReader ir = new InputStreamReader(is,"Shift_JIS");
            os = new FileOutputStream("hige.txt");
            OutputStreamWriter ow = new OutputStreamWriter(os,"UTF-8");
            int tmp;
            while((tmp = ir.read()) != -1){
                ow.write(tmp);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            is.close();
            os.close();
        }

こんな感じで書いていたが


        try(FileInputStream is2 = new FileInputStream("hoge.txt");
                FileOutputStream os2 = new FileOutputStream("hige.txt")){
            InputStreamReader ir2 = new InputStreamReader(is2,"Shift_JIS");
            OutputStreamWriter ow2 = new OutputStreamWriter(os2,"UTF-8");
            int tmp;
            while((tmp = ir2.read()) != -1){
                ow2.write(tmp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

こう書ける
AutoCloseableを実装したクラスであれば自動でcloseしてくれる

49
48
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
48