java 1.7 使用try-with-resource方式关闭资源
原创 bluesky 发表于:2019-04-28 11:27:41
  阅读 :226   收藏   编辑

try-with-resource是1.7新的异常处理机制,能够很方便的关闭在try-catch 语句块中使用的资源

java7以前,资源需要明确的关闭,如:

public static void main(String[] args) throws Exception{
	FileInputStream inputStream = null ;
	try {
		inputStream = new FileInputStream("app.txt");
		//TODO
		System.err.println(inputStream.available());
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		if(inputStream != null) {
			inputStream.close();
		}
	}
}

在java7中,每个资源在语句结束时关闭,该资源实现了 java.lang.AutoCloseable,

对于上面的例子可以用try-with-resource 结构这样写

public static void main(String[] args) throws Exception{
	try(FileInputStream inputStream = new FileInputStream("app.txt")){
		//TODO
		System.err.println(inputStream.available());
	}
}

多个使用;分开

public static void main(String[] args) throws Exception{
	try(FileInputStream inputStream = new FileInputStream("app.txt");
		FileInputStream inputStream2 = new FileInputStream("app.txt")){
		//TODO
		System.err.println(inputStream.available());
		System.err.println(inputStream2.available());
	}
}

自定义AutoClosable 

AutoClosable 接口仅仅有一个方法,任何实现了这个接口的方法都可以在try-with-resources结构中使用

public interface AutoClosable {

    public void close() throws Exception;
}

例子

public class MyAutoClosable implements AutoCloseable {
	
	public void exec() {
		System.err.println("exec ... ");
	}

	@Override
	public void close() throws Exception {
		System.err.println("close ... ");
	}
	
	public static void main(String[] args) throws Exception {
		try(MyAutoClosable my = new MyAutoClosable()){
			my.exec();
		}
	}
}

console打印

exec ... 
close ...