java7新特新(一) Try-with-resources (TWR)
2016-07-26 01:07
447 查看
Try-with-resources (TWR)
在处理IO的代码中,我们会使用大量的try...catch()...finally...语法,其中会在finally进行IO的close操作,写过python的都知道,这种操作可以使用try-with-resources操作,幸运的是Java7也有了此特性,比如之前的语法:private void test(URL url, File file) { InputStream is = null; try { is = url.openStream(); OutputStream out = new FileOutputStream(file); try { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) >= 0) out.write(buf, 0, len); } catch (IOException iox) { } finally { try { out.close(); } catch (IOException closeOutx) { } } } catch (FileNotFoundException fnfx) { } catch (IOException openx) { } finally { try { if (is != null) is.close(); } catch (IOException closeInx) { } } } |
try (OutputStream out = new FileOutputStream(file); InputStream is = url.openStream()) { byte[] buf = new byte[4096]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } } |
try ( ObjectInputStream in = new ObjectInputStream(new FileInputStream("someFile.bin")) ) { ... } |
try ( FileInputStream fin = new FileInputStream("someFile.bin"); ObjectInputStream in = new ObjectInputStream(fin) ) { ... } |
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序