Java基础学习总结--IO流关闭

JAVA学习网 2020-03-21 00:28:01

一、为什么java中io流必须关闭

当我们new一个java流对象之后,不仅在计算机内存中创建了一个相应类的实例对象。而且,还占用了相应的系统资源。在内存中的实例对象,当没有引用指向的时候,java垃圾收集器会按照相应的策略自动回收,但是却无法对系统资源进行释放。所以,我们需要主动调用close()方法释放java流对象。

二、释放资源的方法:

1、方法一:
        File file = new File("F:/JavaPractice/IO2/src/test");
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] flush = new byte[1024];
            int len=0;
            while((len=is.read(flush)) != -1) {
                //此处一定要放实际的读取长度,否则会将flush数组中的非读取到的数据也输出,如:默认值0
                System.out.print(new String(flush, 0, len));        
            }
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(is != null) {
                    is.close();
                }
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
2、方法二:

若需要关闭的流较多,可以利用Closeable接口自己封装一个方法

public static void close(Closeable... ios) {    //其实此处应用的是多态原理
        for(Closeable io:ios) {
            try {
                if(io != null) {
                    io.close();
                }
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

补充:public static void close(Closeable... ios),此处的三点并不是省略号,而是可变参数。

可变参数参考

3、方法三:

在java7之后,可以使用try-with-resources语句来释放java流对象,从而避免了try-catch-finally语句的繁琐。

public static void copy(String srcPath, String destPath) {
        //创建源
        File src = new File(srcPath);
        File dest = new File(destPath);
        
        //选择流
        try(FileInputStream is = new FileInputStream(src);
            FileOutputStream os = new FileOutputStream(dest)) { 
            //操作
            byte[] flush = new byte[1024*2];
            int len = 0;
            while((len=is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
            os.flush();
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
Java新手,若有错误,欢迎指正!
阅读(2400) 评论(0)