In Java programming will encounter a lot of problems of shutting down resources, but, often our close is not hundred correct, so there is a new resource manager method Try-with-resource in Java7, this is an important improvement, because no one can manually shut down the resources to do 100% correct, Someone was thinking that when the coin project submitted the proposal, the submitter claimed that two-thirds of the close () usages in the JDK were bug-embarrassed.
JAVA6 Resource Manager approach, shorthand
InputStream in =NULL; Try{ is=Url.openstream (); OutputStream out=Newfileoutputstream (file); ..... out. }Catch(IOException IoE) {//Todo:handle Exception}finally{ Try{ if(Is! =NULL) {is.close (); } }Catch(IOException ioe2) {//Todo:handle Exception } }
But in Java7, we can write this.
New URL ("www.baidu.com"); Try New FileOutputStream (new File ("D://stest.txt")) InputStream in=url.openstream ();) { int len; byte New byte [1024*1024*5]; while (len = in.read (buffer)) >= 0) { output.write (buffer,0, Len);} }
Yes, it is easy to put resources in the parentheses of the try, and this code will be closed automatically when the resource is finished.
Attention:
Try New ObjectInputStream (new FileInputStream ("Somefile.bin"))) { ... }
The problem here is that if there is an error creating objectinputstream from (Somefile.bin), then FileInputStream will not be shut down
The best way to do this is to declare each resource separately
Try New FileInputStream ("Somefile.bin"); New ObjectInputStream (in)) { ... }
java-Resource Manager Try-with-resource