Automatic shutdown of streams and catch multiple exceptions in Java 7 __java

Source: Internet
Author: User
Tags readline

In our normal development work, often need to read and write stream, in this process the most egg pain is a variety of try and catch, and then finally you can not forget to close the flow, so as to avoid the resource leakage, this set down feel particularly bloated. The following is a simple example:

The old resource opens the way
		bufferedreader br = null;
		try {
			br = new BufferedReader (New FileReader (
					"/users/mrsimple/update_hosts.py"));
			StringBuilder sb = new StringBuilder ();
			String line = "";
			while (line = Br.readline ())!= null) {
				sb.append (line). append ("\ n");
			System.out.println (Sb.tostring ());
		} catch (FileNotFoundException e) {
			e.printstacktrace ();
		} catch (IOException e) {
			e.printstacktrace (); c14/>} finally {
			if (br!= null) {
				try {
					br.close ();
				} catch (IOException e) {
					e.printstacktrace ();
				}
			}
		} End of Finaly

Fortunately, Java 7 introduced two very useful features, that is, automatic shutdown of the stream and catch multiple exceptions. The code required to implement the same functionality after using these two new features is as follows:

		Resource Open in Java 7
		try (bufferedreader newbr = new BufferedReader (New FileReader (
				"/users/mrsimple/update_ hosts.py ")) {
			StringBuilder sb = new StringBuilder ();
			String line = "";
			while (line = Newbr.readline ())!= null) {
				sb.append (line). append ("\ n");
			System.out.println (Sb.tostring ());
		} catch (IOException | FileNotFoundException e) {
			e.printstacktrace ();
		}
When you build a Newbr object in a try block, the object shuts down automatically at the end of the block, eliminating the developer from manually shutting down the stream. Catch multiple exceptions also makes the code more concise.

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.