设为首页 加入收藏

TOP

Java try-with-resources
2019-05-12 02:30:33 】 浏览:49
Tags:Java try-with-resources

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

不需要finally中关闭,直接在try中写resource,resource可以是实现了java.lang.AutoClosable和java.io.Closable的所有类

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇docker   kafka 启动 下一篇redis 报错 Redis protected-mode..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目