try-with-resources 自动关闭资源

转至:https://blog.csdn.net/wtopps/article/details/71108342
Java 7增强了try语句的功能——它允许在try关键字后跟一对圆括号,圆括号可以声明,初始化一个或多个资源,此处的资源指得是那些必须在程序结束时必须关闭的资源(比如数据库连接,网络连接等),try语句在该语句结束时自动关闭这些资源。
  为了保证try语句可以正常关闭资源,这些资源实现类必须实现Closeable或AutoCloseable接口,实现这些类就必须实现close方法。

	FileInputStream in = null;
	FileOutputStream os = null;
	try {
		img2.createNewFile();
		in = new FileInputStream(img);
		os = new FileOutputStream(img2);
		byte[] buf = new byte[(int)img.length()];
		in.read(buf);
		os.write(buf);
	} catch (IOException e) {
		e.printStackTrace();
	} finally{
		try {
			//先开后关
			os.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

使用try-with-resource 结构

		try (
			FileInputStream in = new FileInputStream(img);
			FileOutputStream os = new FileOutputStream(img2);
		){
			img2.createNewFile();
			byte[] buf = new byte[(int)img.length()];
			in.read(buf);
			os.write(buf);
		} catch (IOException e) {
			e.printStackTrace();
		}

自定义 实现AutoCloseable接口:

public class Test01 implements AutoCloseable{
	public void print(){
		System.out.println("运行Test01");
	}
	@Override
	public void close() throws Exception {
		System.out.println("关闭资源");
	}
	
	public static void main(String[] args){
		
		try(Test01 test = new Test01();
			){
			test.print();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
}
结果是:
运行Test01
关闭资源
只要是实现了AutoCloseable接口的类 都可以在try-catch语句实现自动关闭资源

猜你喜欢

转载自blog.csdn.net/zf2015800505/article/details/84777699
今日推荐