Java 7新特性-TWR(Try-with-resources)
Try-with-resources (TWR)
在处理IO的代码中,我们会使用大量的try...catch()...finally...语法,其中会在finally进行IO的close操作,写过python的都知道,这种操作可以使用try-with-resources操作,幸运的是Java7也有了此特性,比如之前的语法:
private void test(URL url, File file) { InputStream is = null; try { is = url.openStream(); OutputStream out = new FileOutputStream(file); try { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) >= 0) out.write(buf, 0, len); } catch (IOException iox) { } finally { try { out.close(); } catch (IOException closeOutx) { } } } catch (FileNotFoundException fnfx) { } catch (IOException openx) { } finally { try { if (is != null) is.close(); } catch (IOException closeInx) { } } }
而使用try-with-resources语法,则可以简化为:
try (OutputStream out = new FileOutputStream(file); InputStream is = url.openStream()) { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } }
但是使用try-with-resources的时候还是由可能造成资源没有关闭,比如在try()中有错误时,比如:
try ( ObjectInputStream in = new ObjectInputStream(new FileInputStream("someFile.bin")) ) { ... }
比如文件存在,但却不是写入的对象序列,因此会造成不正常打开,此时ObjectInputStream不能正确初始化,且不会关闭,因此正确的方式是分开资源变量:
try ( FileInputStream fin = new FileInputStream("someFile.bin"); ObjectInputStream in = new ObjectInputStream(fin) ) { ... }
TWR特性是使用了java7的新的接口AutoCloseable,可以使用try-with-resources语法的资源必须实现该接口。而Closeable继承了AutoCloseable,因此我们常用的资源类都可以使用。