Jdk1.8新特性之try()catch{}

在看《Java8函数式编程》时看到的一段代码

public List<String> findHeadings(Reader input) {
    try (BufferedReader reader = new BufferedReader(input)) {
        return reader.lines()
                     .filter(line -> line.endsWith(":"))
                     .map(line -> line.substring(0, line.length() - 1))
                     .collect(toList());
    } catch (IOException e) {
        throw new HeadingLookupException(e);
    }
}            
try (BufferedReader reader = new BufferedReader(input))使用的是jdk1.8的try-with-resource语句,
在try()中创建流对象语句,如果多个,使用';'隔开,该语句确保了每个资源,在语句结束时关闭。
所谓的资源是指在程序完成后,必须关闭的流对象。写在()里面的流对象对应的类都实现了自动关闭接口AutoCloseable
posted @ 2021-07-12 10:09  王鹏vtv  阅读(1776)  评论(0)    收藏  举报