Java try()语句实现try-with-resources异常管理机制
java7 新增特性,对于try语句块中使用到的资源,不再需要手动关闭,在语句块结束后,会自动关闭,类似于python的with..as的用法。
利用这个特性,需要实现AutoCloseable接口,只有一个close方法,实现关闭资源的操作。
public interface AutoCloseable{ public void close() throws Exception; }
所有的流,都实现了这个接口,可以在try()中进行实例化。自定义的类只要实现了这个接口,也可以使用这个特性。
不使用try-with-resources时,使用的资源要在finally中进行释放
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/test.txt"); FileInputStream fis = null; try { fis = new FileInputStream(f); } catch (IOException e) { e.printStackTrace(); <span style="color:transparent">来1源gaodai#ma#com搞*代#码1网</span> } finally { // 在finally 里关闭流 if (null != fis) try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
使用try-with-resources时
形式为try(),括号内可以包含多个语句。
package stream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class TestStream { public static void main(String[] args) { File f = new File("d:/lol.txt"); //把流定义在try()里,try,catch或者finally结束的时候,会自动关闭 try (FileInputStream fis = new FileInputStream(f)) { byte[] all = new byte[(int) f.length()]; fis.read(all); for (byte b : all) { System.out.println(b); } } catch (IOException e) { e.printStackTrace(); } } }
自定义AutoCloseable实现
在TestAutoCloseable的close方法中打印信息
package test; public class TestAutoCloseable implements AutoCloseable{ public TestAutoCloseable() { System.out.println("class TestAutoCloceable"); } public void close() { System.out.println("function close() executed"); } }
测试代码
package test; public class TestFeature { public static void main(String[] args) { // TODO Auto-generated method stub try(TestAutoCloseable testAutoCloseable = new TestAutoCloseable()){ } } }