首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能使用try-with-resources或finally块

不能使用try-with-resources或finally块
EN

Stack Overflow用户
提问于 2013-05-04 07:27:55
回答 1查看 2.2K关注 0票数 0

我的代码正在从web上读取一个HTML页面,我想写出好的代码,所以我想使用try-with-resources或want block来关闭资源。

在下面的代码中,似乎不可能使用它们中的任何一个来结束"in“。

代码语言:javascript
复制
    try {

        URL url = new URL("myurl");
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                url.openStream()));

        String line = "";

        while((line = in.readLine()) != null) {
            System.out.println(line);
        }

        in.close();
    } 
    catch (IOException e) {
        throw new RuntimeException(e);
    }

您是否能够使用try-with-resources或same来编写相同的代码?

EN

回答 1

Stack Overflow用户

发布于 2013-05-04 08:24:26

我看不出在以下方面有什么特别的困难:

代码语言:javascript
复制
    try (BufferedReader in = new BufferedReader(new InputStreamReader(
            new URL("myurl").openStream()))) {

        String line = "";
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

这不就是你要找的吗?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16368974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档