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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM