優(yōu)化代碼結(jié)構(gòu)之寫個(gè)公共工具來關(guān)閉流
最近在看Guava的文件流相關(guān)的源碼時(shí),偶爾看到了Files工具類中是如何關(guān)閉輸入與輸出流的,本著學(xué)習(xí)的態(tài)度,把這部分單獨(dú)整理出來.
在Files中FileByteSource的read()方法時(shí)這樣定義的:
@Override public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return readFile(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
看到 Closer的用法了嗎?覺得十分好用,看下Closer的注釋
A Closeable that collects Closeable resources and closes them all when it is closed. This is intended to approximately emulate the behavior of Java 7's try-with-resources statement in JDK6-compatible code. Running on Java 7, code using this should be approximately equivalent in behavior to the same code written with try-with-resources. Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the thrown exception as a suppressed exception.
This class is intended to be used in the following pattern:
Closer closer = Closer.create();
try {
InputStream in = closer.register(openInputStream());
OutputStream out = closer.register(openOutputStream());
// do stuff
} catch (Throwable e) {
// ensure that any checked exception types other than IOException that could be thrown are
// provided here, e.g. throw closer.rethrow(e, CheckedException.class);
throw closer.rethrow(e);
} finally {
closer.close();
}}
說白了,就是一個(gè)收集可關(guān)閉資源然后進(jìn)行統(tǒng)一關(guān)閉這些資源的工具類.
待續(xù)...