tags:

views:

45

answers:

1

I have the below code to read from a URL object:

URL url= new URL("http://datasource.com");     
BufferedReader reader = new BufferedReader(
                                new InputStreamReader(url.openStream()));

After I am done getting the data, is this sufficient to close and release all the resrouces:

reader.close();

I did not see a method for URL to close it, like URL.close()...but wondering if I shouldn't do something more like this:

InputStreamReader inputStreamReader = new InputStreamReader(url.openStream());
BufferedReader reader = new BufferedReader(inputStreamReader);
// Do Stuff
inputStreamReader.close();
reader.close();
+1  A: 

Close the reader is enough, Because Reader/InputStream classes are implemented by decorator pattern, the close action will propagate to decoratee.

The source in the BufferedReader, the reader(variable in) is closed, too:

public void close() throws IOException {
    synchronized (lock) {
        if (!isClosed()) {
            in.close();
            buf = null;
        }
    }
}

The source in the InputStreamReader, the input stream is closed, too:

@Override
public void close() throws IOException {
    synchronized (lock) {
        // BEGIN android-added
        if (decoder != null) {
            decoder.reset();
        }
        // END android-added
        decoder = null;
        if (in != null) {
            in.close();
            in = null;
        }
    }
}
qrtt1