Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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してくれる

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away