大白话之AutoClosable接口 | try-with-resources:JDK1.7的新特性,提高重复回收效率
前言 无论是使用文件IO流,还是网络Socket流,都免不了调用close()将流关闭。如果需要操作的流过多,就会导致混乱。 一旦忘记将关闭方法放到finally中,很有可能出现流未被关闭,占用大量内存空间的问题。 流程简化 对比 try-catch-finally AC ac = null; AC2 ac2 = null; try { ac = new AC(); ac2 = new AC2(); } catch (Exception e) { } finally { ac.close(); ac2.close(); } try-with-resources try (AC ac = new AC(); AC2 ac2 = new AC2()) { } catch (Exception e) { } 可以很明显的看到,try-with-resources会自动调用类中的close()方法,简化了流程,提高了代码的整洁度。 AutoCloseable AutoCloseable是Java的内置接口,继承这个接口并且按要求新建close()方法,该类就能被try-with-res....