Java Reference
In-Depth Information
Despite
Listing 3-30
being somewhat more readable than
Listing 3-29
, there is still
alotofboilerplatethankstoeachfinallyblockrequiringatrystatementtocloseafile.
Thisboilerplateisnecessary;itsremovalresultsinanew
IOException
possiblybe-
ing thrown from the catch block, which would mask a previously thrown
IOExcep-
tion
.
Automatic Resource Management
Listings3-29
and
3-30
arehideousbecauseoftheamountofcodethat'snecessarytoen-
surethateachfileisclosed.However,youdon'thavetocodethisway.Instead,youcan
use Java's try-with-resources statement to automatically close
resources
(objects that
must be closed when they are no longer needed) on your behalf.
The try-with-resources statement minimally consists of a try block that features the
following syntax:
try ([
resource declaration
; ...]
resource declaration
)
{
// code to execute
}
Reserved word
try
is followed by a round bracket-delimited and semicolon-separ-
ated list of resource declarations. Each of the declared resources is to be closed when
execution leaves the try block, either normally or via a thrown exception. The follow-
erably:
static void copy(String srcFile, String dstFile) throws
IOException
{
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream
fos
=
new
FileOut-
putStream(dstFile))
{
int b;
while ((b = fis.read()) != -1)
fos.write(b);
}
}
The example's try-with-resources statement declares two file resources that must be
closed; theresource declarations areseparated withamandatory semicolon. Whenthe