JDK1.7 new feature-Auto Close class

Source: Internet
Author: User
Tags stringbuffer
The JDK has the ability to automatically turn off classes after 1.7, and the advent of this feature provides considerable help for a variety of shutdown resources, and here we talk about auto-closing classes. After JDK1.7, an important interface was introduced, and an important method structure was modified: 1, autocloseable auto-shutdown Interface 2, try () {}--catch{}--finally{} Some of the corresponding resources also implemented the interface, such as PreparedStatement, Connection, InputStream, OutputStream and so on resource interface.
Interface implementation class to override the close () method, the resource to be closed is defined in try (), so that when the program finishes executing, the resource is automatically closed. Custom class if you want to automatically shut down, only need to implement the Autocloseable interface rewrite the close () method, but also only implement the Autocloseable interface can be, the custom class into the try () block, otherwise the compilation can not pass, the example code is as follows:
<pre name= "code" class= "Java" >class Readtxt extends autoclassable {
	@Override public
	Void Close () throws Exception {
		System.out.println ("Readtxt close");
	}

	public string Readtextvalue (string path) {
		StringBuffer sb = new StringBuffer ();
		Try (bufferedreader br = new BufferedReader (new FileReader (path))) {
			int line;
			while (line = Br.read ())!=-1) {
				sb.append (br.readline () + "\ n")
			}
		}
		return sb.tostring ();
	}
}

class Maintest {public
	static void Main (string[] args) {
		try (readtxt rt = new Readtxt ()) {
			String L ine = Rt.readtextvalue ("g:\\ Learning document \\test.txt");
			System.out.println (line);}}}




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.