Java 7 New try-with-resources statement, automatic resource release

Source: Internet
Author: User


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.