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接口
以上就是用try语句关闭资源实例的详细内容。