try-with-resources

概述

在使用IO流的代码中,通常既要处理异常又要关闭流,jdk7之前的这套处理代码冗长,在随后的JDK7进行了优化,JDK9又进行了一次优化。

JDK7之前

        FileReader fr = null;
        try {
            fr = new FileReader("3.txt");
            int i = fr.read();
            System.out.println((char) i);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

JDK7版本

可以通过在try后的小括号内写入IO流的创建语句,作用域不受限制的同时还兼有finally代码块的作用,大大简化了代码。缺点是小括号内只能放入一个IO对象。

//        FileReader fr = null;
        try (FileReader fr = new FileReader("3.txt")){
//            fr = new FileReader("3.txt");
            int i = fr.read();
            System.out.println((char) i);
        } catch (IOException e) {
            e.printStackTrace();
        }/*finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }*/

JDK9版本

        FileReader fr = new FileReader("3.txt");
        PrintWriter pw = new PrintWriter("4.txt");
        try (fr;pw){
            int i = fr.read();
            System.out.println((char) i);
            pw.println("天天开心");
        } catch (IOException e) {
            e.printStackTrace();
        }

try后的小括号中可以放入多个IO对象,使用更加简便。

posted on 2021-10-19 17:34  技术小伙伴  阅读(50)  评论(0)    收藏  举报