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(); } } } } }
- ##Use finally block to close physical resources to ensure that the closing operation is always will be executed.
The above method causes the finally block code to be very bloated and the readability of the program is reduced.
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(); } } }
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)
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!