下面的方法将一个文件复制到另一个文件,但是它的设计中存在一个隐患,很难被发现。
static void copy(String src, String dest)throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
如果你还在使用上面这种方式来关闭
Closeable对象的话,那么本文一定会改变你的编程习惯的。
问题在
finally语句中,close方法也可能会抛出IOException异常。如果这正好发现在in.close被调用之时,那么这个异常就会阻止out.close被调用,从而使输出流保持在开放状态。
所以这个程序使得
finally可能被意外结束。解决方式是将每一个close都包装在一个try语句块中。从java 5.0版本开始,可以利用Closeable接口:
finally {
closeIgnoringException(in);
closeIgnoringException(out);
}
private static void closeIgnoringException(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ex) {
}
}
}