Re: Closing Files that Weren't Successfully Opened
On 15 Mrz., 08:52, Lawrence D'Oliveiro <l...@geek-
central.gen.new_zealand> wrote:
In message <4pp258-hg4....@dagon.net>, Dagon wrote:
It's not uncommon to see code like:
finally {
if (someResource != null) {
try {
someResource.close();
} catch (exceptionsCloseCanThrow ecct) {
logger.error("WTF!", ecct);
}
}
}
This is ugly, and an admission that you haven't tracked the state of yo=
ur
resource very well ...
What's the alternative?
The alternative is to create and assign outside the block and do the
close in finally - unconditionally:
final FileInputStream fin = new FileInputStream("foo.txt");
try {
final byte[] buffer = new byte[1024];
for (int read;(read = fin.read(buffer))>=0;) {
// do whatever with buffer[0,read[
}
}
finally {
// no null or other check needed!
fin.close();
}
If you want to ensure an exception from close() does not shadow
another error you can do
static void close(Closable c) {
try {
c.close();
}
catch (IOException e) {
// ignore or log
}
}
and use that in the finally block.
If you want BufferedReader you can do
final BufferedReader reader =
new BufferedReader(new InputStreamReader(new
FileInputStream("foo.txt")));
try {
for (String line; (line = reader.readLine()) != null;) {
System.out.println("Found line: " + line);
}
}
finally {
reader.close();
}
I would declare IOException on the method that contains this code to
leave IO error handling to callers.
Kind regards
robert