Starting with the Java 7 Build 105 version, the Java 7 compiler and runtime environment supports the new try-with-resources statement, called ARM block (Automatic Resource Management), automatic resource management.
The new statement support includes streams and any resources that can be closed, for example, in general we will write the following code to free up resources:
Private static void Custombufferstreamcopy (file source, file target) {InputStream FIS =NULL; OutputStream fos =NULL;Try{FIS =NewFileInputStream (source); FOS =NewFileOutputStream (target);byte[] buf =New byte[8192];intI while((i = Fis.read (BUF))! =-1) {Fos.write (buf,0, i); } }Catch(Exception e) {E.printstacktrace (); }finally{Close (FIS); Close (FOS); }} Private static void close (closeable closable) {if(Closable! =NULL) {Try{Closable.close (); }Catch(IOException e) {E.printstacktrace (); } }}
The code is quite complicated, and the management of the exception is cumbersome.
Instead, use the Try-with-resources statement to simplify the code as follows:
Privatestaticvoidcustombufferstreamcopy (file source, file target){ trynew FileInputStream ( source); New FileOutputStream (target)) { bytenewbyte[8192]; int i; while ((i = Fis.read (BUF))! =-1) { 0, i); } } Catch (Exception e) { e.printstacktrace (); }}
In This example, the data flow is automatically closed after the try has been executed, provided that these closed resources must implement the Java.lang.AutoCloseable interface.
Java 7 New try-with-resources statement, automatic resource release