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);}}}