Sams Teach Yourself C in 21 Days

(singke) #1
26: }
27: catch (IOException e) {
28: System.out.println(“Error: “ + e.toString());
29: fileError = true;
30: }
31: if (!fileError)
32: System.out.println(“File successfully written.”);
33: else
34: System.out.println(“An error occurred - file not written.”);
35: }
36: }

(if an error occurs, writing to a: with no diskette inserted):
Error: java.io.FileNotFoundException: a:\output.txt(The device is not
ready)
An error occurred - file not written.
(if no error occurs):
Enter lines of text to put in the file.
Enter a blank line when done.
This is line 1.
This is line 2.
This is the last line.
File successfully written.
Lines 1 to 5 should need no explanation. Lines 6 and 9 set up a BufferedReader
object to read lines of text from the keyboard. This technique was covered on
Bonus Day 5. Line 10 opens the tryblock where exceptions may occur. Lines 11 and 12
set up the FileWriterandBufferedWriterobjects that will be used to write text to the
file. This code creates a file named output.txt in the root folder on drive C:. Be sure to
change this name if you want to.
Lines 13 and 14 display instructions to the user. Line 15 sets up a boolean doneflag.
Line 16 starts a whileloop that will execute as long as the doneflag is false. Line 17
reads a line of text from the keyboard, and line 18 checks the length of the text. If the
length is not 0 (some text was entered), a new line character is added to the end of the
text (line 19), and the text is written to the file (line 20). If the length is 0 , indicating a
blank line was entered, the doneflag is set to truewhich terminates the loop.
Lines 27 to 30 are the catchblock for this code. If an exception is caught, the error mes-
sage is displayed and the fileErrorvariable is set to true. If no exception occurs, of
course, this code is not executed at all.

748 Bonus Day 6

LISTINGB6.2 continued

OUTPUT

OUTPUT

ANALYSIS

41 448201x-Bonus6 8/13/02 11:23 AM Page 748

Free download pdf