首页 > 技术文章 > java try-with-resources打开资源文件

kehao 2021-03-25 20:22 原文

原来的try catch finally处理方法

public class test1 {

	public static void main(String[] args) {
		FileInputStream file = null;
		try {
			file = new FileInputStream(new File("demo.txt"));
			/*
			 * 处理这个文件的操作
			 */
		} catch(IOException e){
			e.printStackTrace();
		} finally {
			//关闭资源
			if(file != null) {
				try {
					file.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
	}
}

发现这种操作很繁琐,代码也很多,那有没有什么简便的方法呢?就像python里面的with语句一样呢

try with resources 方法如下

public class test1 {

	public static void main(String[] args) {
		try(InputStream is = new FileInputStream("demo.txt")){
			/*
			 * 处理这个文件的操作
			 */
		}catch (IOException e) {
			//这里处理FileNoFoundExceotion等异常
			e.printStackTrace();
		} 
	}
}

支持定义多个 resources
通过 JDBC 查询数据库时,会依次创建 Connection、Statment、ResultSet,并且这三个资源都需要关闭,那么可以这样写:

try (Connection connection = DriverManager.getConnection(url, user, password);
     Statement statement = connection.createStatement();
     ResultSet resultSet = statement.executeQuery("SELECT ...")) {
    // ...
} catch (Exception e) {
    // ...
}

多个 resources 的关闭顺序
如果在 try 中定义了多个 resources,那么它们关闭的顺序和创建的顺序是相反的。上面的例子中,依次创建了 Connection、Statment、ResultSet 对象,最终关闭时会依次关闭 ResultSet、Statment、Connection,所以不用担心 Connection 会先 close。

参考文档如下:
https://zhuanlan.zhihu.com/p/163106465
https://blog.csdn.net/weixin_43347550/article/details/106208765

推荐阅读