• java之IO流的关闭


    1.在finally中关闭流;

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

    2.在关闭多个流时因为嫌麻烦将所有关流的代码丢到一个try中

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

    3.在循环中创建流,在循环外关闭,导致关闭的是最后一个流

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

    4.在Java7中,关闭流这种繁琐的操作就不用我们自己写了

      只要实现的自动关闭接口(Closeable)的类都可以在try结构体上定义,java会自动帮我们关闭,及时在发生异常的情况下也会。可以在try结构体上定义多个,用分号隔开即可,如:

    try (OutputStream out = new FileOutputStream("");OutputStream out2 = new FileOutputStream("")){  
        // ...操作流代码  
    } catch (Exception e) {  
        throw e;  
    }  
  • 相关阅读:
    python脚本2_输入2个数比较大小后从小到大升序打印
    python脚本1_给一个半径求圆的面积和周长
    配置双机互信
    如何在 CentOS7 中安装 Nodejs
    Git 服务器搭建
    docker安装脚本
    CentOS7下安装Docker-Compose
    Linux 文件锁
    6 系统数据文件和信息
    bash脚本编程之二 字符串测试及for循环
  • 原文地址:https://www.cnblogs.com/jpfss/p/9835071.html
Copyright © 2020-2023  润新知