java中正确关闭流

在操作java流对象后要将流关闭释放此流有关的所有系统资源,不然OutputStream会大量占用系统内存,可能会导致内存溢出。

因为OutputStream的各种write()方法可能会抛出IO异常,而不能将流关闭,大致有以下三种情况不一定能将流真正关闭:

1.在try中关流,而没在finally中关流

try{
    File file = new File("D:\\file.txt");
    OutputStream out = new FileOutputStream(file);
    // ...操作流
    out.close();
}catch(Exception e){
    e.printStackTrace();
}

正确写法:

OutputStream out = null;
try{
    File file = new File("D:\\file.txt");
    out = new FileOutputStream(file);
    // ...操作流
}catch(Exception e){
    e.printStackTrace();
} finally {
    try {
        if(out != null){
            out.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

2.在关闭多个流时,用一个try去关闭多个流

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

正确写法:

OutputStream out1 = null;
OutputStream out2 = null;
try{
    File file = new File("D:\\file.txt");
    out1 = new FileOutputStream(file);
    out2 = new FileOutputStream(file);
    // ...操作流
}catch(Exception e){
    e.printStackTrace();
} finally {
    // 先try关闭第一个
    try {
        if(out1 != null){
            out1.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    // 再try关闭第二个
    try {
        if(out2 != null){
            out2.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

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

OutputStream out = null;
try{
    File file = new File("D:\\file.txt");
    for(int i=0; i<3; i++){
        out = new FileOutputStream(file);
        // ...操作流
    }
}catch(Exception e){
    e.printStackTrace();
} finally {
    // 此时关闭的是for循环完的最后一个out
    try {
        if(out != null){
            out.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

正确写法:

for(int i=0; i<3; i++){
    OutputStream out = null;
    try{
        File file = new File("D:\\file.txt");
        out = new FileOutputStream(file);
        // ...操作流
    } catch(Exception e){
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(code,java,流处理)