before Java7, Java's exception handling structure is a try catch Finally, try code block open resources, their close all have to put in finally, very cumbersome syntax rules, I believe the vast number of developers spit trough. For A simple example, look at the following:
Public Static voidMain (string[] args) {File file=NewFile ("/workspace/test.txt") ; FileInputStream FIS=NULL ; Try{FIS=Newfileinputstream (file); StringBuffer Buffer=NewStringBuffer (); intC; while((c =fis.read ())! =-1) {buffer.append (Char) c); } System.out.print (buffer); } Catch(FileNotFoundException e) {//Logging//Deal Exception}Catch(IOException e) {//Loggin//Deal Exception}finally { if(FIS! =NULL) { Try{fis.close (); } Catch(IOException e) {//Deal Exception } } }}
starting with JAVA7, the default syntax is to support the default auto-shutdown within the try code block, writing code that does not need to be displayed. The above example is modified as follows:
Public Static voidMain (string[] args) {File file=NewFile ("/workspace/test.txt") ; Try(FileInputStream FIS =Newfileinputstream (file)) {StringBuffer buffer=NewStringBuffer (); intC; while((c =fis.read ())! =-1) {buffer.append (Char) c); } System.out.print (buffer); } Catch(FileNotFoundException e) {//Logging//Deal Exception}Catch(IOException e) {//Loggin//Deal Exception }}
This syntax optimization makes the code a lot more refreshing. The code inside the try () is automatically closed by default, which is equivalent to implicitly executing a finally block of code. Java7 is how to do, do not put the inside of the try () to perform the close operation of the variables, this will not be a problem ah. Later we found that JAVA7 also introduced an interface
Public Interface autocloseable { voidthrows Exception;}
and all the previous resource classes that need to be closed have implemented this interface. This interface represents a variable that is placed inside a try () and automatically shuts down resources as long as the AUTOCLOSEABLE,JVM is implemented. This once again shows the power of the interface.
Java7 try-with-resources