When you write Try-catch, you encounter objects such as streams, joins, and so on, and you must add a finally statement to close the objects.
Today, we suddenly find that the with module of the try can omit the action of the Finally manual shutdown, which can be
The object is defined in the With module, and then, after the try statement completes, the object is automatically close, provided the object is required
Realized theautocloseableOrcloseableInterface.
Then found that this feature is actually introduced in the JAVA7, and now all java9, only to find. Very outdated AH!!!
For example, the current wording:
try (BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file));) { byte[] buffer = new byte[1024]; int len = -1; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); bos.flush(); } } catch (IOException e) { e.printStackTrace();}
That's enough, but there were multiple finally, and the object definition had to be put in front of the try:
BufferedInputStream bis = null;BufferedOutputStream bos = null;try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(new FileOutputStream(file)); byte[] buffer = new byte[1024]; int len = -1; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); bos.flush(); }} catch (IOException e) { e.printStackTrace();}finally{ if(null!=bis){ bis.close(); } if(null!=bos){ bos.close(); }}
The function of the WITH statement block in the Try-catch module in Java