You've already learned how to chain an OutputStreamWriter to a FileOutputStream and an InputStreamReader to a FileInputStream. Although this isn't hard, Java provides two simple utility classes that take care of the details, java.io.FileWriter and java.io.FileReader .
20.8.1. FileWriter
The FileWriter class is a subclass of OutputStreamWriter that writes text files using the platform's default character encoding and buffer size. If you need to change these values, construct an OutputStreamWriter on a FileOutputStream instead.
public class FileWriter extends OutputStreamWriter
This class has four constructors:
public FileWriter(String fileName) throws IOException public FileWriter(String fileName, boolean append) throws IOException public FileWriter(File file) throws IOException public FileWriter(FileDescriptor fd)
The first constructor opens a file and positions the file pointer at the beginning of the file. Any text in the file is overwritten. For example:
FileWriter fw = new FileWriter("36.html");
The second constructor allows you to specify that new text is appended to the existing contents of the file rather than overwriting it by setting the second argument to TRue. For example:
FileWriter fw = new FileWriter("36.html", true);
The third and fourth constructors use a File object and a FileDescriptor, respectively, instead of a filename to identify the file to be written to. Any preexisting contents in a file so opened are overwritten.
You use the standard Writer methods like write( ), flush( ), and close( ) to write the text in the file.
20.8.2. FileReader
The FileReader class is a subclass of InputStreamReader that reads text files using the platform's default character encoding. If you need to change the encoding, construct an InputStreamReader chained to a FileInputStream instead.
public class FileReader extends InputStreamReader
This class has three constructors that differ only in how the file to be read is specified:
public FileReader(String fileName) throws FileNotFoundException public FileReader(File file) throws FileNotFoundException public FileReader(FileDescriptor fd)
Only the constructors are declared in this class. You use the standard Reader methods like read( ), ready( ), and close( ) to read the text in the file.
|
Basic I/O
Introducing I/O
Output Streams
Input Streams
Data Sources
File Streams
Network Streams
Filter Streams
Filter Streams
Print Streams
Data Streams
Streams in Memory
Compressing Streams
JAR Archives
Cryptographic Streams
Object Serialization
New I/O
Buffers
Channels
Nonblocking I/O
The File System
Working with Files
File Dialogs and Choosers
Text
Character Sets and Unicode
Readers and Writers
Formatted I/O with java.text
Devices
The Java Communications API
USB
The J2ME Generic Connection Framework
Bluetooth
Character Sets