Sams Teach Yourself C in 21 Days

(singke) #1
More Java Techniques 745

BD6


Java exceptions are a complex topic. You will see some details of how they are used in
the section on file input/output.

Reading and Writing Files ..................................................................................


Java has a complete set of classes for all types of file input and output. Covering all the
details is well beyond the scope of this chapter, so I will limit coverage to basic text
input and output.

Reading Text Files ........................................................................................


Reading from text files is done with the FileReaderandBufferedReaderclasses, part of
the java.io package. When you create an instance of theFileReaderclass, you pass it the
name (including path, if required) of the file you want to read:
FileReader inFile = new FileReader(filename);
Then you use the reference to the FileReaderobject to create an instance of
Bufferedreader:
BufferedReader buff = new Bufferedreader(inFile);
Now you are ready to read text from the file using thereadLine method. This method
reads a single line of text and returns it as a type String. If the end of the file has been
reached, it returns the special value null. By repeatedly calling readLineuntil it returns
null, you can read the entire contents of a text file a line at a time.
Because file manipulations are full of possibilities for error, you must use Java’s error
handling to catch exceptions. You’ll see how this is done in the sample program in
Listing B6.1. Be sure to change the filename in line 6 as required.

LISTINGB6.1 reading.c. Reading text from a file a line at a time
1: import java.io.*;
2: public class ReadTextFile {
3: public static void main(String args[]) {
4: String s;
5: try {
6: FileReader inFile = new FileReader(“c:\\test.txt”);
7: BufferedReader buff = new BufferedReader(inFile);
8: boolean endOfFile = false;
9: while (!endOfFile) {
10: s = buff.readLine();
11: if (s == null)
12: endOfFile = true;
13: else

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

Free download pdf