首页 文章资讯内容详情

Java9中的Try-With-Resources语句有哪些改进

2026-06-03 1 花语

在Java7中引入了Try-with-Resources。使用它的目的是在资源被使用后自动关闭。限制是资源需要在try之前或try语句内部声明,否则会引发编译错误

Java9改进了try-with-resources,不再需要在try语句中声明对象。

在下面的示例中,我们实现了“try-with-resources”的概念。

示例

import java.io.*; public class TryWithResourceTest { public static void main(String[] args) throws FileNotFoundException { String line; Reader reader = new StringReader("nhooo.com"); BufferedReader breader = new BufferedReader(reader); try(breader) { while((line = breader.readLine()) != null) { System.out.println(line); } } catch(IOException ioe) { ioe.printStackTrace(); } } }

输出结果

nhooo.com