The function of the WITH statement block in the Try-catch module in Java

Source: Internet
Author: User

When you write Try-catch, you encounter objects such as streams, joins, and so on, and you must add a finally statement to close the objects.
Today, we suddenly find that the with module of the try can omit the action of the Finally manual shutdown, which can be
The object is defined in the With module, and then, after the try statement completes, the object is automatically close, provided the object is required
Realized theautocloseableOrcloseableInterface.
Then found that this feature is actually introduced in the JAVA7, and now all java9, only to find. Very outdated AH!!!
For example, the current wording:

try (BufferedInputStream bis = new BufferedInputStream(is);             BufferedOutputStream bos = new BufferedOutputStream(                     new FileOutputStream(file));) {            byte[] buffer = new byte[1024];            int len = -1;            while ((len = bis.read(buffer)) != -1) {                bos.write(buffer, 0, len);                bos.flush();            }        } catch (IOException e) {            e.printStackTrace();}

That's enough, but there were multiple finally, and the object definition had to be put in front of the try:

BufferedInputStream bis =  null;BufferedOutputStream bos = null;try  {                    bis = new BufferedInputStream(is);        bos = new BufferedOutputStream(new FileOutputStream(file));      byte[] buffer = new byte[1024];      int len = -1;      while ((len = bis.read(buffer)) != -1) {           bos.write(buffer, 0, len);           bos.flush();       }} catch (IOException e) {      e.printStackTrace();}finally{         if(null!=bis){                    bis.close();            }            if(null!=bos){                    bos.close();        }}

The function of the WITH statement block in the Try-catch module in Java

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.