Home > Java > javaTutorial > body text

Close resource instances using try statements

PHP中文网
Release: 2017-06-21 17:02:01
Original
1582 people have browsed it

java7 enhanced try statement to close resources

Traditional way to close resources

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();
                }
            }
        }
    }
}
Copy after login
  • ##Use finally block to close physical resources to ensure that the closing operation is always will be executed.

  • Before closing each resource, first ensure that the reference variable referencing the resource is not null.

  • Use a separate try...catch block for each physical resource to close the resource to ensure that exceptions caused when closing the resource will not affect the closing of other resources.

    The above method causes the finally block code to be very bloated and the readability of the program is reduced.

java7 enhanced try statement to close resources

In order to solve the above traditional method problems, Java7 has added a new function to automatically close resources. try statement. It allows a pair of parentheses to be followed by the try keyword, in which one or more resources can be declared and initialized. The resources here refer to those resources that must be explicitly closed when the program ends (database connections, network connections, etc.) , the try statement will automatically close these resources at the end of the statement.

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();
        }

    }
}
Copy after login
The try statement that automatically closes the resource is equivalent to including an implicit finally block (used to close the resource), so this try statement can have neither a catch block nor a finally block.

Note:

  • The resource that is automatically closed must implement the Closeable or AutoCloseable interface. (Closeable is a sub-interface of AutoCloseable. The close() method statement in the Closeeable interface throws IOException; the close() method statement in the AutoCloseable interface throws Exception)

  • The closed resource must be declared and initialized in parentheses after the try statement. If the program has a try statement that needs to automatically close resources, it can include multiple catch blocks and a finally block.

Java7 has rewritten almost all "resource classes" (including various classes of file IO, Connection, Statement and other interfaces of JDBC programming...). After rewriting All resource classes implement AutoCloseable or Closeable interface

The above is the detailed content of Close resource instances using try statements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!