简体   繁体   English

关闭BufferedReader和InputStreamReader

[英]Closing BufferedReader and 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. 这段代码正在创建BufferedReaderInputStreamReader导致的内存泄漏问题,我认为可能会发生一些异常。 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){

}

It would be safer to close your stream using a try..finally block. 使用try..finally块关闭流更安全。 You might also use a StringBuilder as it is designed for concatenating strings. 您也可以使用StringBuilder因为它是为连接字符串而设计的。 You should also avoid catching Exception and doing nothing with it. 您还应该避免捕获Exception并对其执行任何操作。 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. 这可能不是你想要的,在这种情况下,当你读取每一行时append("\\n")

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);
}

The code isn't pretty but won't be creating a memory leak. 代码不漂亮,但不会造成内存泄漏。 I suggest you use a memory profiler to determine where your memory is being used. 我建议你使用内存分析器来确定你的内存使用位置。 Otherwise you are just guessing even if you have ten + years experience performance tuning in Java ;) 否则你只是猜测即使你有10年以上的Java经验性能调优;)

A better alternative is to use Java 7 更好的选择是使用Java 7

URL url = new URL(sMyUrl);
try(BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
  while ((str = in.readLine()) != null) {
     jsonString.append(str).append("\n");
  }
}

If you have Java 6 or older you can use. 如果您使用Java 6或更早版本,则可以使用。

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
try {
  while ((str = in.readLine()) != null) {
     jsonString.append(str).append("\n");
  }
} finally {
  in.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM