正确关闭流

/**
 * 关闭给定的io流
 */
public static void close(Closeable...closes){
    for (Closeable closeable : closes) {
        try {
            if(closeable!=null){
                closeable.close();                  
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 调用close()方法
 */
 public static void main(String[] args) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(new File("D:\1.bmp"));
        fos = new FileOutputStream(new File("D:\1_copy.bmp"));
        //其他代码
        //......
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        close(fos,fis);
    }
}

这样做的好处是,可以让每一个流都得到正确的关闭。

原文地址:https://www.cnblogs.com/turbo30/p/14052307.html