Java Reference
In-Depth Information
< Day Day Up >
Puzzle 41: Field and Stream
This method copies one file to another and was designed to close every stream it creates, even if it
encounters I/O errors. Unfortunately, it doesn't always do this. Why not, and how can you fix it?
static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
Solution 41: Field and Stream
This program seems to have all the bases covered. The stream fields (
in
and
out
) are initialized to
null
and set to the new streams as soon as they are created. The
finally
block closes the stream
referred to by each field if it is non-null. An error during the copy would cause an
IOException
, but
the
finally
block would still execute before the method returns. What could go wrong?
The problem is in the
finally
block itself. The
close
method can throw an
IOException
too. If
Search WWH ::
Custom Search