考虑这样一种场景,你要为系统编写一个下载文件并缓存到本地的功能,你会用到InputSteam和OutputStream类,你可能会这么写:InputStream is = null;OutputStream os = null;try { is = new FileInputStream(""); os = new FileOutputStream(""); //下载文件的代码 //保存到本地的代码} catch (FileNotFoundException e) { e.printStackTrace();} finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } }}在finally代码块中,为了关闭两个IO流居然写了14行代码,假如每次用到IO的时候都写一大堆if……else,也挺烦的,有没有什么办法可以用一行代码就搞定呢?查看InputStream和OutputStream抽象类源代码,发现他们都实现了共同的接口Closeable,事实上,java中所有Stream类都必须实现这个接口,那么,这下就好办了。我们可以设计一个工具类,如下:public class IOUtil { public static void close(Closeable… closeableList) { try { for (Closeable closeable : closeableList) { if (closeable != null){ closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } }}那么,在finally代码块中就可以这样写:finally{/* 这些代码都可以省略 if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } }*///只需要下面这一行代码就可以了 IOUtil.close(is, os);}是不是方便了很多呢?这个工具类用到了可变参数,接口隔离的思想。这样写代码,不仅仅只是方便而已,代码的可读性也好了很多,不是吗?