在我们关闭流时,通常是close放到 finally 中,并在 close 前判断是否为 null。但close也会 throw IOException,所以在在 finally 中 也需要 try catch 一下,于是代码就很长。如下:
try {
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
而如果使用IOUtils.closeQuietly,就方便多了,如下:
try {
} catch (IOException e) {
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}