JAVA正确的关闭IO流方式

写法 1:在 try 中关流,而没在 finally 中关流

try {
    OutputStream out = new FileOutputStream("file");
    // ...操作流代码
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

当操作流代码报错的时候,这种写法会导致流无法正常的关闭,因此不推荐采用

正确的操作方式,应该在finally里面完成,实例代码如下:

OutputStream out = null;
try {
    out = new FileOutputStream("file");
    // ...操作流代码
} catch (Exception e) {
    e.printStackTrace();
} finally {
    // 在 finally 中进行关闭,确保一定能被执行
    try {
        if (out != null) {
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

写法 2:在关闭多个流时,将其放在一个 try 中

在关闭多个流时,有的同学嫌弃麻烦,将其放在一个 try 中完成,实例代码如下:

OutputStream out1 = null;
OutputStream out2 = null;
try {
    out1 = new FileOutputStream("file");
    out2 = new FileOutputStream("file");
    // ...操作流代码
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out1 != null) {
            // 如果此处出现异常,则out2流没有被关闭
            out1.close();
        }
        if (out2 != null) {
            out2.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这种写法下,当out1.close出异常的时候,out2.close是不会被正常关闭的,因此不推荐采用

正确的操作方式,应该是一个一个的close,别偷懒,实例代码如下:

OutputStream out1 = null;
OutputStream out2 = null;
try {
    out1 = new FileOutputStream("file");
    out2 = new FileOutputStream("file");
    // ...操作流代码
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out1 != null) {
            out1.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        if (out2 != null) {
            out2.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

写法 3:在循环中创建流,在循环外关闭

有的同学在循环操作多个文件时,在循环外关闭文件流,实例代码如下:

OutputStream out = null;
try {
    for (int i = 0; i < 10; i++) {
        out = new FileOutputStream("file");
        // ...操作流代码
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out != null) {
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

表面看上去好像没有问题,但是实际上创建了 10 个 IO 流,try 里面的逻辑执行完成之后,只是把最后的一个 IO 流对象赋予给了out参数。也就是当程序执行完毕之后,只关闭了最后一个 IO 流,其它 9 个 IO 流没用被手动关闭,因此不推荐采用

正确的操作方式,应该是在循环体内close,别偷懒,实例代码如下:

for (int i = 0; i < 10; i++) {
    OutputStream out = null;
    try {
        out = new FileOutputStream("file");
        // ...操作流代码
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

写法 4:关闭多个流时,没用遵循后定义先释放原则

有的同学在操作多个文件流时,操作完成之后,依照先后次序进行关闭文件流,实例代码如下:

FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
    fos = new FileOutputStream("file");
    bos = new BufferedOutputStream(fos);
    // ...操作流代码
} catch (Exception e){

} finally {
    // 依次关闭流
    try {
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        // 此处会报 java.io.IOException: Stream Closed 错误
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

按照先后顺序关闭文件流,这种写法下,有可能会报java.io.IOException: Stream Closed错误。

原因是BufferedOutputStream依赖于FileOutputStream,如果直接关闭FileOutputStream流,再次关闭BufferedOutputStream,会提示源头已经被关闭,缓存区数据无法输出。

正确的操作方式,应该遵循后定义先释放的原则,实例代码如下:

FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
    fos = new FileOutputStream("file");
    bos = new BufferedOutputStream(fos);
    // ...操作流代码
} catch (Exception e){

} finally {
    // 后定义先释放
    try {
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 写法 5:jdk7 及以上版本,推荐采用 try-with-resources 写法

try-with-resources是 JDK 7 中引入的一个新的异常处理机制,它能让开发人员不用显式的释放try-catch语句块中使用的资源。

以上文为例,可以改成如下写法:

try (FileOutputStream fos = new FileOutputStream("file");
     BufferedOutputStream bos = new BufferedOutputStream(fos)){
    // ...操作流代码
} catch (Exception e){
    e.printStackTrace();
}

 try-with-resources释放资源的操作,也是遵循的后定义先释放的原则

写法 6:使用包装流时,只需要关闭最后面的包装流即可

包装流是指通过装饰设计模式实现的 IO 流类,其目的是对底层流的功能进行扩展,在实际数据传输的时候,还是使用底层流进行传输。比如缓存字节输出流BufferedOutputStream就是一个包装流,目的是对字节输出流提供一个缓存区功能,让数据输出效率更高。

在使用到包装流的时候,我们只需要关闭最后面的包装流即可。

以上文为例,改写的实例代码如下:

InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
    is = new FileInputStream("file");
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    // ...操作流代码
} catch (Exception e){
    e.printStackTrace();
} finally {
    // 关闭包装流,也会自动关闭 InputStream 流
    try {
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

总结:

在上文中,我们提到只要是 IO 流都建议大家手机关闭资源,但是在 Java 中有一种流,它是不需要手动关闭的,比如内存读写流:ByteArrayInputStreamByteArrayOutputStream

不同于指向硬盘的流,ByteArrayInputStreamByteArrayOutputStream其实是伪装成流的字节数组存储在内存中(把它们当成字节数据来看就好了),他们不会锁定任何文件句柄和端口,如果不再被使用,字节数组会被垃圾回收掉,所以不需要关闭。

当 IO 流是指向存储卡 / 硬盘 / 网络等外部资源的流,是一定要手动关闭的。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大道之简

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值