关闭BufferedReader和InputStreamReader [英] Closing BufferedReader and InputStreamReader

查看:477
本文介绍了关闭BufferedReader和InputStreamReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码正在创建内存泄漏问题 BufferedReader InputStreamReader 我认为可能会发生一些例外情况。我该怎么改变它?

This piece of code is creating memory leak issues cause of BufferedReader and InputStreamReader which I think might be happening cause of some exceptions. How should I change it?

try{
    URL url = new URL(sMyUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    while ((str = in.readLine()) != null) {
        jsonString += str;
    }
    in.close();
}catch(Exception e){

}


推荐答案

使用 try..finally 块关闭流更安全。您也可以使用 StringBuilder ,因为它是为连接字符串而设计的。您还应该避免捕获异常并且不执行任何操作。此外,您的代码是连接行没有任何换行符。这可能不是你想要的,在这种情况下,追加(\ n)当你读取每行时。

It would be safer to close your stream using a try..finally block. You might also use a StringBuilder as it is designed for concatenating strings. You should also avoid catching Exception and doing nothing with it. Also, your code is concatenating lines without any line-breaks. This may well not be what you want, in which case append("\n") when you read each line in.

这是一个带有这些修改的版本:

Here's a version with those modifications:

StringBuilder json = new StringBuilder();
try {
    URL url = new URL(sMyUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    try {
        String str;
        while ((str = in.readLine()) != null) {
            json.append(str).append("\n");
        }
    } finally {
        in.close();
    }
} catch (Exception e) {
    throw new RuntimeException("Failed to read JSON from stream", e);
}

这篇关于关闭BufferedReader和InputStreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆