首先来看看常用的try-finally: public static void main(String[] args) throws Exception{ InputStream inputStream = new FileInputStream(new File("E:/test.txt")); try{ inputStream.read(); }catch (IOException e){ e.printStackTrace(); }finally { inputStream.close(); } }
然后是try-with-resources:
public static void main(String[] args) throws Exception{ InputStream inputStream; try (InputStream in = new FileInputStream(new File("E:/test.txt"));){ inputStream=in; } //测试是否关闭 try { inputStream.read(); } catch (IOException e) { System.out.println("已关闭"); //如果流已经关闭,这里会报 } }
建议使用第二种,这个是Java7新加入的;
相比于第一种常用的,第二种优点:
1.代码更为简洁明了,可读性更佳;
2.会自动关闭括号内定义的流,很好的避免了因为粗心出现的流未关闭的现象。