Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
48
Help us understand the problem. What is going on with this article?
@FSMS

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

48
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  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
FSMS

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
48
Help us understand the problem. What is going on with this article?