In your last approach , Resource leak
warning as shown by eclipse is correct according to the rules of closing streams. closing the innermost stream is only closing that stream but not the other streams that has wrapped up that stream. But closing the outermost stream is one time operation that will automatically close all the underlying streams.
As specified in the article Always close streams :
If multiple streams are chained together, then closing the one which
was the last to be constructed, and is thus at the highest level of
abstraction, will automatically close all the underlying streams. So,
one only has to call close on one stream in order to close (and flush,
if applicable) an entire series of related streams.
So In my opinion following code is solution for your case:
public static void read(String filename) throws IOException {
String charsetName = "UTF-8";
InputStream file = null;
InputStreamReader reader = null;
BufferedReader buffer = null;
try
{
file = new FileInputStream(filename);
reader = new InputStream(file,charsetName);
buffer = new BufferedReader(reader);
buffer.readLine();
}
finally
{
closeQuietly(buffer,reader,file);
}
}
EDIT
As suggested by @jtahlborn the code written within finally block is wrapped within a utility method as follows:
public static void closeQuietly(Closeable... closeables)
{
if(closeables == null)
{
return;
}
for (Closeable c : closeables)
{
doCloseQuietly(c);
}
}
public static void doCloseQuietly(Closeable c)
{
try
{
if (c != null)
{
c.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}