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
BufferedReader br = null;
You are declaring a variable without assigning it (null
doesn't count - it is a useless assignment in this case). This is a code "smell" in Java (ref Effective Java; Code Complete for more on variable declaration).
}finally{
br.close();
isr.close();
}
First, you only need to close the top-most stream decorator (br
will close isr
). Secondly, if br.close()
threw an exception, isr.close()
would not be called, so this is not sound code. Under certain exception conditions, your code will hide the originating exception with a NullPointerException
.
isr = new InputStreamReader(connection.getInputStream());
If the (admittedly unlikely) event that the InputStreamReader
constructor threw any kind of runtime exception, the stream from the connection would not be closed.
Make use of the Closeable
interface to reduce redundancy.
Here is how I would write your code:
URLConnection connection = new URL("www.example.com").openConnection();
InputStream in = connection.getInputStream();
Closeable resource = in;
try {
InputStreamReader isr = new InputStreamReader(in);
resource = isr;
BufferedReader br = new BufferedReader(isr);
resource = br;
String response = br.readLine();
} finally {
resource.close();
}
Note that:
A while back, I spent some time thinking about how to avoid leaking resources/data when things go wrong.