1

In a very usual operation of parsing JSON, we do something like this

StringBuilder sb = new StringBuilder();
BufferedReader br = null;
        try {
            URL requestUrl = new URL(url);
            URLConnection con = requestUrl.openConnection();
            br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            int cp;
            try {
                while ((cp = br.read()) != -1) {
                    sb.append((char) cp);
                }
            }
            catch(Exception e){
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br != null){
               try{
                   br.close();
               }catch (IOException e){
                   e.printStackTrace();
               }
            }
        }

Here I am just closing the buffered reader. Is this enough, or I should close the Input stream as well ?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Ankit
  • 4,426
  • 7
  • 45
  • 62

1 Answers1

1

Closing BufferedReader is enough.

If you look at the source of BufferedReader.close(), you'll see it closes the underlying reader:

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

And from Reader.close()'s javadocs:

Closes the stream and releases any system resources associated with it.

Amila
  • 5,195
  • 1
  • 27
  • 46