240617-java中try-with-resources的使用

77 阅读1分钟

try-with-resources简介:

阿里巴巴java开发手册提到:finally块必须对资源对象、流对象进行关闭。

image.png

try-with-resources与java7中引入,常用于需要关闭资源的异常捕获,相比于try-catch-finally,简化了对资源的管理。

try-catch-finally关闭资源

代码冗杂

    /**
     * 手动关闭
     */
    public static void test1() {
        String filePath = "D:\\test1\\test1.txt";
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(filePath));
            fileInputStream = new FileInputStream(new File(filePath));
            // 写
            fileOutputStream.write("ab1024".getBytes(Charset.defaultCharset()));
            // 读取
            int data = fileInputStream.read();
            while (data != -1) {
                System.out.print((char) data);
                data = fileInputStream.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭写流
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 关闭读流
                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
 
        }
    }

try-with-resources关闭资源

public class test2 {
    public static void main(String[] args) {
        try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("E:\\in.txt")));
             BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("E:\\out.txt")))) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

jdk9中对资源的声明做了改进,更简洁了

public class Demo {
    public static void main(String[] args) throws FileNotFoundException {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("E:\\in.txt")));
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("E:\\out.txt")));
        try (bin;bout) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}