我使用这个小的静态实用程序类,其原则是如果你真的必须做一些(任何事情)冗长的错误处理或最终阻塞,那么至少撕掉它并实现一次该死的东西,而不是乱扔你的应用程序代码分心手头的任务:
package krc.utilz.io;
import java.io.Closeable;
import krc.utilz.reflectionz.Invoker;
public abstract class Clozer
{
/**
* close these "streams"
* @param Closeable... "streams" to close.
*/
public static void close(Closeable... streams) {
Exception x = null;
for(Closeable stream : streams) {
if(stream==null) continue;
try {
stream.close();
} catch (Exception e) {
if(x!=null)x.printStackTrace();
x = e;
}
}
if(x!=null) throw new RuntimeIOException(x.getMessage(), x);
}
/**
* Close all the given objects, regardless of any errors.
* <ul>
* <li>If a given object exposes a close method then it will be called.
* <li>If a given object does NOT expose a close method then a warning is
* printed to stderr, and that object is otherwise ignored.
* <li>If any invocation of object.close() throws an IOException then
* <ul>
* <li>we immediately printStackTrace
* <li>we continue to close all given objects
* <li>then at the end we throw an unchecked RuntimeIOException
* </ul>
* </ul>
* @param Object... objects to close.
*/
public static void close(Object... objects) {
Exception x = null;
for(Object object : objects) {
if(object==null) continue;
try {
Invoker.invoke(object, "close", new Object[]{} );
} catch (NoSuchMethodException eaten) {
// do nothing
} catch (Exception e) {
e.printStackTrace();
x = e;
}
}
if(x!=null) throw new RuntimeIOException(x.getMessage(), x);
}
}
try{stream1.close();}catch{} try{stream2.close();}catch{}
请注意,与常见的cop-out不同,最后一个关闭异常(如果有)仍然被抛出。
干杯。基思。