Java中使用try-with-resource优雅的关闭io流

前言

最近看到一篇关于串流的关闭方法,通过编译器自动生成关闭串流源码,行之有效。
转载自博主: Java劝退师、
https://blog.csdn.net/qq_41389354/article/details/111896446

    JAVA的一大特性就是JVM会对内部资源实现自动回收,即自动GC,给开发者带来了极大的便利。但是JVM对外部资源的引用却无法自动回收,例如数据库连接,网络连接以及输入输出IO流等,这些连接就需要我们手动去关闭,不然会导致外部资源泄露,连接池溢出以及文件被异常占用等。

    传统的手动释放外部资源一般放在一般放在try{}catch(){}finally{}机制的finally代码块中,因为finally代码块中语句是肯定会被执行的,即保证了外部资源最后一定会被释放。同时考虑到finally代码块中也有可能出现异常,finally代码块中也有一个try{}catch(){},这种写法是经典的传统释放外部资源方法,显然是非常繁琐的。

传统写法操作io流

例如如下读取的文件的io流,我们之前可能会这样写

public class Main {
    
    
    public static void main(String[] args) {
    
    
        FileInputStream fileInputStream =null;
        try {
    
    
            fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt")); //打开流
            byte[] bytes = new byte[1024];
            int line = 0;    
            //读取数据
            while ((line = fileInputStream.read(bytes))!= -1){
    
    
                System.out.println(new String(bytes,0,line));
            }
 
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            if (fileInputStream != null){
    
     //不为空
                try {
    
    
                    fileInputStream.close(); //关闭流
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

使用try-with-resource写法优雅操作io流

public class Main {
    
    
    public static void main(String[] args) {
    
    
        //把打开流的操作都放入try()块里
        try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt"))) {
    
    
            byte[] bytes = new byte[1024];
            int line = 0;
            while ((line = fileInputStream.read(bytes))!= -1){
    
    
                System.out.println(new String(bytes,0,line));
            }
 
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

在try()中可以编写多个文件io流或网络io流。让我们看看java编译器是怎么帮我们实现的

借助idea查看编译后的代码

在这里插入图片描述

可以看到编译后的代码,java编译器自动替我们加上了关闭流的操作。所以跟我们自己关闭流是一样的。try-with-resource这样优雅的写法还是不错的,让代码看起来不那么臃肿。

注意jdk1.7以后才可以用

猜你喜欢

转载自blog.csdn.net/jerrygaoling/article/details/112556358