java7增强的try语句关闭资源

java7增强的try语句关闭资源

传统的关闭资源方式

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Student implements Serializable {
	private String name;

	public Student(String name) {
		this.name = name;
	}
}

public class test2 {
	public static void main(String[] args) throws Exception {
		Student s = new Student("WJY");
		Student s2 = null;
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			//创建对象输出流
			oos = new ObjectOutputStream(new FileOutputStream("b.bin"));
			//创建对象输入流
			ois = new ObjectInputStream(new FileInputStream("b.bin"));
			//序列化java对象
			oos.writeObject(s);
			oos.flush();
			//反序列化java对象
			s2 = (Student) ois.readObject();
		} finally { //使用finally块回收资源
			if (oos != null) {
				try {
					oos.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
  • 使用finally块来关闭物理资源,保证关闭操作总是会被执行。
  • 关闭每个资源之前首先保证引用该资源的引用变量不为null。
  • 为每一个物理资源使用单独的try...catch块来关闭资源,保证关闭资源时引发的异常不会影响其他资源的关闭。

以上方式导致finally块代码十分臃肿,程序的可读性降低。

java7增强的try语句关闭资源

为了解决以上传统方式的问题, Java7新增了自动关闭资源的try语句。它允许在try关键字后紧跟一对圆括号,里面可以声明、初始化一个或多个资源,此处的资源指的是那些必须在程序结束时显示关闭的资源(数据库连接、网络连接等),try语句会在该语句结束时自动关闭这些资源。


public class test2 {
	public static void main(String[] args) throws Exception {
		Student s = new Student("WJY");
		Student s2 = null;
		try (//创建对象输出流
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.bin"));
				//创建对象输入流
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.bin"));
       )
    {
			//序列化java对象
			oos.writeObject(s);
			oos.flush();
			//反序列化java对象
			s2 = (Student) ois.readObject();
		}

	}
}

自动关闭资源的try语句相当于包含了隐式的finally块(用于关闭资源),因此这个try语句可以既没有catch块,也没有finally块。

注意:

  • 被自动关闭的资源必须实现Closeable或AutoCloseable接口。(Closeable是AutoCloseable的子接口,Closeeable接口里的close()方法声明抛出了IOException,;AutoCloseable接口里的close()方法声明抛出了Exception)
  • 被关闭的资源必须放在try语句后的圆括号中声明、初始化。如果程序有需要自动关闭资源的try语句后可以带多个catch块和一个finally块。

Java7几乎把所有的“资源类”(包括文件IO的各种类,JDBC编程的Connection、Statement等接口……)进行了改写,改写后的资源类都实现了AutoCloseable或Closeable接口

原文地址:https://www.cnblogs.com/Onlywjy/p/6938789.html