Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 19: Input/Output: Exploring java.io 579


Reader

Readeris an abstract class that defines Java’s model of streaming character input. It
implements theCloseableandReadableinterfaces. All of the methods in this class
(except formarkSupported( )) will throw anIOExceptionon error conditions. Table 19-3
provides a synopsis of the methods inReader.


Writer

Writeris an abstract class that defines streaming character output. It implements theCloseable,
Flushable, andAppendableinterfaces. All of the methods in this class throw anIOException
in the case of errors. Table 19-4 shows a synopsis of the methods inWriter.


FileReader

TheFileReaderclass creates aReaderthat you can use to read the contents of a file. Its two
most commonly used constructors are shown here:


FileReader(StringfilePath)
FileReader(FilefileObj)

Either can throw aFileNotFoundException. Here,filePathis the full path name of a file, and
fileObjis aFileobject that describes the file.
The following example shows how to read lines from a file and print these to the standard
output stream. It reads its own source file, which must be in the current directory.


// Demonstrate FileReader.
import java.io.*;


class FileReaderDemo {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;


while((s = br.readLine()) != null) {
System.out.println(s);
}

fr.close();
}
}


FileWriter

FileWritercreates aWriterthat you can use to write to a file. Its most commonly used
constructors are shown here:


FileWriter(StringfilePath)
FileWriter(StringfilePath, booleanappend)
FileWriter(FilefileObj)
FileWriter(FilefileObj, booleanappend)

They can throw anIOException. Here,filePathis the full path name of a file, andfileObjis aFile
object that describes the file. Ifappendistrue, then output is appended to the end of the file.

Free download pdf