以前写 try-catch 时, 遇到一些流, 连接等对象, 必定需要添加 finally 语句来关闭这些对象.
今天突然发现 try 的 with 模块可以省略在 finally 手动关闭的动作, 可以通过将这些
对象定义在 with 模块中, 然后在 try 语句完成后, 自动 close 对象, 前提需要该对象
实现了 AutoCloseable 或 Closeable 接口.
然后发现, 这个特性其实在 java7 中就引入了, 现在都 java9 了, 才发现. 很落伍啊!!!
例如现在的写法:
- 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();
- }
这样就够了, 但是以前得多个 finally, 并且对象定义还得放到 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();
- }
- }
来源: http://www.bubuko.com/infodetail-2669135.html