我们深知在操作Java流对象后要将流关闭,但往往事情不尽人意,大致有以下几种不能一定将流关闭的写法:

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

try {
OutputStream out = new FileOutputStream("");
// ...操作流代码
out.close();
} catch (Exception e) {
e.printStackTrace();
}
正确写法:
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流没有被关闭
}
if (out2 != null) {
out2.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

正确写法:

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.在循环中创建流,在循环外关闭,导致关闭的是最后一个流

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

正确写法:

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();
}
}
}

PS:在Java7中,关闭流这种繁琐的事情再也不用我们自己敲代码了:

try (OutputStream out = new FileOutputStream("")){
// ...操作流代码
} catch (Exception e) {
e.printStackTrace();
}只要实现的自动关闭接口(Closeable)的类都可以在try结构体上定义,java会自动帮我们关闭,及时在发生异常的情况下也会。可以在try结构体上定义多个,用分号隔开即可,如:
try (OutputStream out = new FileOutputStream("");OutputStream out2 = new FileOutputStream("")){
// ...操作流代码
} catch (Exception e) {
throw e;
}