优化你的代码

优化代码结构之写个公共工具来关闭流

最近在看Guava的文件流相关的源码时,偶尔看到了Files工具类中是如何关闭输入与输出流的,本着学习的态度,把这部分单独整理出来.
在Files中FileByteSource的read()方法时这样定义的:

@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();
   }}

说白了,就是一个收集可关闭资源然后进行统一关闭这些资源的工具类.
待续...

你可能感兴趣的:(优化你的代码)