Java resource closing

Posted by Bob on Stack Overflow See other posts from Stack Overflow or by Bob
Published on 2010-06-15T11:01:21Z Indexed on 2010/06/15 11:12 UTC
Read the original article Hit count: 352

Hi,

I'm writing an app that connect to a website and read one line from it. I do it like this:

try{
        URLConnection connection = new URL("www.example.com").openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = rd.readLine();
        rd.close();
    }catch (Exception e) {
        //exception handling
    }

Is it good? I mean, I close the BufferedReader in the last line, but I do not close the InputStreamReader. Should I create a standalone InputStreamReader from the connection.getInputStream, and a BufferedReader from the standalone InputStreamReader, than close all the two readers? I think it will be better to place the closing methods in the finally block like this:

InputStreamReader isr = null;
BufferedReader br = null;
try{
    URLConnection connection = new URL("www.example.com").openConnection();
    isr = new InputStreamReader(connection.getInputStream());
    br = new BufferedReader(isr);
    String response = br.readLine();
}catch (Exception e) {
    //exception handling
}finally{
    br.close();
    isr.close();
}

But it is ugly, because the closing methods can throw exception, so I have to handle or throw it.

Which solution is better? Or what would be the best solution?

© Stack Overflow or respective owner

Related posts about java

Related posts about exception-handling