Java Reference
In-Depth Information
Note Do not be concerned if you find this listing's file-oriented code difficult to
grasp;IwillformallyintroduceI/Oandthelisting'sfile-orientedtypesin Chapter8 . I'm
Listing 3-29 presents an application that copies bytes from a source file to a des-
tination file via a nested pair of try blocks. The outer try block uses a object to open the source file for reading; the inner
tryblockusesa objecttocreatethedestinationfile
for writing, and also contains the file-copying code.
If the fis = new FileInputStream(args[0]); expression throws
FileNotFoundException , execution flows into the outer try statement's catch
(FileNotFoundException fnfe) block, which outputs a suitable message to
the user. Execution then enters the outer try statement's finally block.
The outer try statement's finally block closes an open source file. However, when
FileNotFoundException isthrown,thesourcefileisnotopen—noreferencewas
assignedto fis .Thefinallyblockuses if (fis != null) todetectthissituation,
and does not attempt to close the file.
If fis = new FileInputStream(args[0]); succeeds, execution flows
into the inner try block, which executes fos = new FileOut-
putStream(args[1]); .Ifthisexpressionthrows FileNotFoundException ,
executionmovesintotheinnertry's catch (FileNotFoundException fnfe)
block, which outputs a suitable message to the user.
This time, execution continues with the inner try statement's finally block. Because
the inner finally block to the outer finally block.
FileInputStream 's and FileOutputStream 's close() methods throw
IOException when a file is not open. Because IOException is checked, these
Search WWH ::

Custom Search