Try () {} = = in Java try-with-resources resource Auto-release

Source: Internet
Author: User

A while ago saw a structure of exception handling, but always forget to send blog learning, today read and see this exception handling,

Try () {



}catch () {


}


Similar to this structure.

This structure is called try-with-resources. Automatic resource release.

This feature exists from the JDK1.7.


For example, the following code:

private static void Custombufferstreamcopy (file source, file target) {
InputStream FIS = null;
OutputStream fos = null;
try {
FIS = new FileInputStream (source);
FOS = new FileOutputStream (target);

byte[] buf = new byte[8192];

int i;
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 above code is very complex for exception handling,

For resources to close is also very cumbersome, then you can compare with the following:


private static void Custombufferstreamcopy (file source, file target) {
Try (inputstream fis = new FileInputStream (source);
OutputStream fos = new FileOutputStream (target)) {

byte[] buf = new byte[8192];

int i;
while ((i = Fis.read (BUF))! =-1) {
Fos.write (buf, 0, I);
}
}
catch (Exception e) {
E.printstacktrace ();
}
}



This code uses this Try-with-resources resource auto-release feature.


In Try () {

}catch () {



The resources are automatically closed after the end, and released. There is no need to write off manually.


Try () {} = = in Java try-with-resources resource Auto-release

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.