java se1.7 try-with-resources 使用

来源:互联网 发布:剑灵灵族捏脸数据图 编辑:程序博客网 时间:2024/06/13 11:59

在进行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.AutoCloseablejava.io.Closeable的对象都可以做为资源自动关闭

原创粉丝点击