The second pattern (the check for null one) could be amended as :
public static void readSO2(String filename) throws IOException {
String charsetName = "UTF-8";
InputStream file = null;
InputStreamReader reader = null;
BufferedReader buffer = null;
try {
file = new FileInputStream(filename);
reader = new InputStreamReader(file, charsetName);
buffer = new BufferedReader(reader);
buffer.readLine();
} finally {
try {
if (buffer != null) buffer.close();
else if (reader != null) reader.close();
else if (file != null) file.close();
} catch (IOException e) {
// report at least
e.printStackTrace();
}
}
}
- Pros : one close, one possible exception, no flush needed (for output streams)
- Cons : still inelegant : null dance, one must be careful in the order of the ifs, no way to generalize
So question still stands.