Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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){

}
like image 222
Pit Digger Avatar asked Aug 30 '12 14:08

Pit Digger


People also ask

Should you close InputStreamReader?

It's important to close any resource that you use. in. close will close BufferedReader, which in turn closes the resources that it itself uses ie. the InputStreamReader.

Do you need to close a BufferedReader?

When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.

What happens if BufferedReader is not closed?

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect. So, if you don't close(), system resources may be still associated with the reader which may cause memory leak.


1 Answers

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);
}
like image 124
ᴇʟᴇvᴀтᴇ Avatar answered Oct 06 '22 02:10

ᴇʟᴇvᴀтᴇ