Sams Teach Yourself C in 21 Days

(singke) #1
14: System.out.println(s);
15: }
16: buff.close();
17: }
18: catch (IOException e) {
19: System.out.println(“An error occurred: “ + e.toString());
20: }
21: }
22: }

(if the file does not exist):
An error occurred: java.io.FileNotFoundException: c:\test.txt
(The system cannot find the file specified)
(if the file exists):
This is a test file.
It contains 3 lines of text.
This is the last line.

746 Bonus Day 6

LISTINGB6.1 continued

OUTPUT

OUTPUT

In today’s lesson, we use file path names based on Windows and DOS. If you
are using Unix or a different operating systems, you will want to use the
appropriate file format. For example, unix machines tend to use a forward
slash instead of a backslash.

Note


Your output will depend on the contents of the file you select, of course. Lines 1
to 4 should be familiar to you by now and do not require any explanation. Line 5
starts a tryblock, marking the code where Java should look for exceptions. Line 6 cre-
ates a type FileReaderobject, associating it with the file c:\test.txt. Note the use of \\to
represent a single backslash in the filename, because \is one of Java’s escape characters.
Line 7 creates a BufferedReaderobject associated with the FileReaderobject just cre-
ated. Line 8 creates a type Booleanvariable to serve as the end of file flag. Line 9 sets
up a whileloop that will repeat as long as endOfFileis false. Line 10 reads a line of
text from the file. Lines 11 to 15 test the value of the input. If it is null,endOfFileis set
totrue, thus ending the loop. Otherwise the input text is displayed on the screen.
Finally, line 16 closes the file. Line 17 marks the end of the tryblock.
Lines 18 to 20 are the catchblock that is executed if the code in the tryblock throws an
exception of type IOException. This code displays the error message shown in the first
output above.

ANALYSIS

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

Free download pdf