Java 9中的try-with-resources有哪些改进?

WBOY
WBOY 转载
2023-09-10 12:45:03 1014浏览

Java 9中的try-with-resources有哪些改进?

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

Java 9改进了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("tutorialspoint"); BufferedReader breader = new BufferedReader(reader); try(breader) { while((line = breader.readLine()) != null) { System.out.println(line); } } catch(IOException ioe) { ioe.printStackTrace(); } } }

输出

tutorialspoint

以上就是Java 9中的try-with-resources有哪些改进?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除