我经常看到这种类型的资源清理:
InputStream in = null;
try {
in = new FileInputStream(file);
// ...
} finally {
if (in != null) {
in.close();
}
}
我一直使用以下风格:
final InputStream in = new FileInputStream(file);
try {
// ...
} finally {
in.close();
}
但是我错过了什么吗?前者有我没有看到的优点吗?
最佳答案
我怀疑它是为了避免有两个嵌套的 try/catch block 而不是一个。
InputStream in = null;
try {
in = new FileInputStream(file);
// ...
} catch(IOException ioe) {
// handle exception.
} finally {
IOUtils.closeQuietly(in);
}
第二种情况不完整。
try {
final InputStream in = new FileInputStream(file);
try {
// ...
} finally {
in.close();
}
} catch(IOException e) {
// handle exception
}
如果您有多个文件,这可能会变得非常困惑。
关于java - Java 1.6 中清理资源的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199711/