在我們關閉流時,通常是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);
}