try-catch-resource介绍


了解 try-catch-resource 前,我们可以回忆一下基础的 try-catch-finally 处理文件流的方式:

public class try_catch_resources {
    public static void main(String[] args) throws Exception {
        BufferedOutputStream br = null;
        try {
            br = new BufferedOutputStream(new FileOutputStream("out.txt"));
            br.write("this is test text".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            br.close();
        }
    }
}

如果你有学过 Python 的话,应该认识一个关键字 with

with open("file1.txt", "r") as file1:
    content1 = file1.read()

使用这个关键字后,你将不需要手动 close file,Java中同样也可以实现,就是使用 try-catch-resource

try-catch-resouce:在try的时候指定需要回收的资源,代码将会自动close

try-catch-resource的使用


首先, resource 并不是关键字,我们只需要在 try 的 () 中创建流即可:

public class try_catch_resources {
    public static void main(String[] args) throws Exception {
        try (BufferedOutputStream br = new BufferedOutputStream(new FileOutputStream("out.txt"));) {
            br.write("this is test text".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

自定义AutoCloseable

当然,close方法也是可以自定义的,如:

public class try_catch_resources {
    public static void main(String[] args) throws Exception {
        try (MyResource myResource = new MyResource()) {
            myResource.sout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  
class MyResource implements AutoCloseable {
  
    @Override
    public void close() {
        System.out.println("自定义close触发");
    }
  
    public void sout() {
        System.out.println("myResource sout");
    }
  
}