java-Resource Manager Try-with-resource

Source: Internet
Author: User

In Java programming will encounter a lot of problems of shutting down resources, but, often our close is not hundred correct, so there is a new resource manager method Try-with-resource in Java7, this is an important improvement, because no one can manually shut down the resources to do 100% correct, Someone was thinking that when the coin project submitted the proposal, the submitter claimed that two-thirds of the close () usages in the JDK were bug-embarrassed.

JAVA6 Resource Manager approach, shorthand

InputStream in =NULL; Try{ is=Url.openstream (); OutputStream out=Newfileoutputstream (file);    ..... out. }Catch(IOException IoE) {//Todo:handle Exception}finally{        Try{            if(Is! =NULL) {is.close (); }        }Catch(IOException ioe2) {//Todo:handle Exception        }    }

But in Java7, we can write this.

New URL ("www.baidu.com");         Try New FileOutputStream (new File ("D://stest.txt")) InputStream in=url.openstream ();) {            int  len;             byte New byte [1024*1024*5];              while (len = in.read (buffer)) >= 0) {                output.write (buffer,0, Len);}        }

Yes, it is easy to put resources in the parentheses of the try, and this code will be closed automatically when the resource is finished.

Attention:

Try New ObjectInputStream (new FileInputStream ("Somefile.bin"))) {            ...        }

The problem here is that if there is an error creating objectinputstream from (Somefile.bin), then FileInputStream will not be shut down

The best way to do this is to declare each resource separately

Try New FileInputStream ("Somefile.bin");                 New ObjectInputStream (in)) {            ...        }

java-Resource Manager Try-with-resource

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.