All,
I am trying to ensure that a file I have open with BufferedReader is closed when I catch an IOException, but it appears as if my BufferedReader object is out o
It's better not to deal with null
- the general idiom for resource acquisition and release in Java is :
final Resource resource = acquire();
try { use(resource); }
finally { resource.release(); }
so:
public static List readFiletoArrayList(String fileName,
List fileArrayList, String charsetName) {
fileArrayList.clear(); // why fileArrayList.removeAll(fileArrayList) ?
try {
InputStream file = new FileInputStream(fileName);
try {
InputStreamReader reader = new InputStreamReader(file, charsetName);
BufferedReader buffer = new BufferedReader(reader);
for (String line = buffer.readLine(); line != null; line = buffer
.readLine()) {
fileArrayList.add(line);
}
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace(); // you do not want this to hide an
// exception thrown earlier so swallow it
}
}
} catch (IOException e) {
fileArrayList.clear(); // returned empty. Dealt with in client
}
return fileArrayList;
}
See my points here
If you are using a reader you must specify the encoding as I am doing here. If you want to read bytes forget about the reader. Also if you use readLine()
you must forget about the end of line characters - if this is a concern consider omitting the BufferedReader
entirely.