在进行java编程的过程中,出现文件流未关闭或者connection未关闭的情况,很难发现而且出现的问题也不知道是哪里的问题,无意中发现javase1.7开始出现try-with-resources,可以很方便的为我们处理忘记关闭文件资源的情况。
String path = "C:\\Users\\ASUS\\Desktop\\11.txt";
try(BufferedReader br = new BufferedReader(new FileReader(path))){
System.out.println(br.readLine().toString());
} catch (FileNotFoundException e) {
System.out.println(1);
e.printStackTrace();
} catch (IOException e) {
System.out.println(2);
e.printStackTrace();
} finally {
System.out.println(3);
}
try(Connection con = DBUtil.getConnection()){
System.out.println(8888);
} catch (SQLException e) {
System.out.println(11);
e.printStackTrace();
} finally {
System.out.println(22);
}
书写比常规的try-catch要简单很多
注:java.lang.AutoCloseable
或java.io.Closeable
的对象都可以做为资源自动关闭