以前使用try catch-finally都是捕获异常,然后流关闭等等,代码总是这样的:好比往FileOutputStream写东西:
@Test public void test2() throws IOException { File file = new File("E://test"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream(file); try { System.out.println("do something..."); fileOutputStream.write("aaa".getBytes()); fileOutputStream.flush(); } catch (Exception e) { System.out.println("do ..."); } finally { fileOutputStream.close(); } }这样写很难受,可以进行优化,将FileOutputStream fileOutputStream = new FileOutputStream(file)放到try()里面,也可以放多个,
@Test public void test2() throws IOException { File file = new File("E://test"); if (!file.exists()) { file.createNewFile(); } try( FileOutputStream fileOutputStream = new FileOutputStream(file);) { System.out.println("do something..."); fileOutputStream.write("aaa".getBytes()); fileOutputStream.flush(); } catch (Exception e) { System.out.println("do ..."); } }try()里每个声明的变量类型都必须是Closeable的子类,就一个close方法;相当于系统自动将关闭操作放到了finally里面而不需要我们自己写了,很nice;