是否有一种不那么丑陋的方式来处理 close()
异常以关闭两个流然后:
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
try {
copy(in, out);
} finally {
try {
in.close();
} catch (Exception e) {
try {
// event if in.close fails, need to close the out
out.close();
} catch (Exception e2) {}
throw e; // and throw the 'in' exception
}
}
out.close();
}
更新:以上所有代码都在一个 try-catch 中,感谢您的警告。
终于(在答案之后):
可以使用Execute Around idiom 来完成一个好的实用方法。 (感谢汤姆·霍廷)。
最佳答案
这是正确的惯用语(而且效果很好):
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputFileName);
out = new FileOutputStream(outputFileName);
copy(in, out);
finally {
close(in);
close(out);
}
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
//log the exception
}
}
这个工作正常的原因是,在你到达 finally 之前抛出的异常将在你的 finally 代码完成后抛出,前提是你的 finally 代码本身不会抛出异常或以其他方式异常终止。
编辑:从 Java 7(和 Android SDK 19 - KitKat)开始,现在有一个 Try with resources 语法来使这个更干净。 this question 中解决了如何处理该问题.
关于Java io丑陋的try-finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2699209/