Java Reference
In-Depth Information
FIGURE 4.6
The writer classes of the java.io package
Writer
BufferedWriter
CharArrayWriter
PipedWriter
PrintWriter
StringWriter
OutputStreamWriter
FileWriter
FilterWriter
To demonstrate how the classes work, let's look at an example of a program that reads
characters from a fi le. The following code reads in a single character at a time from a fi le
named alphabet.txt , which contains the 26 characters of the alphabet in lowercase:
FileReader in = new FileReader(“alphabet.txt”);
int c = 0;
while((c = in.read()) != -1) {
System.out.print((char) c);
}
The output of the code is
abcdefghijklmnopqrstuvwxyz
In the real world, reading one character from a fi le is not done because it is ineffi cient
and typically the data in the fi le represents data types beyond characters. Typically, you
take a FileReader and attach a high-level stream to it to buffer and fi lter the data, which
we discuss in the next section.
Low-Level vs. High-Level Streams
Another important concept to understand about the java.io package is the difference
between a low-level stream and a high-level stream (where stream in this context also refers
to reader and writer streams):
Low-level input and output streams connect to the source of the data.
High-level input and output streams are chained to an existing stream. Most high-level
streams filter the data and convert it into Java data types.
For example, a FileReader is a low-level stream because it connects to a fi le on your fi le
system. The purpose of FileReader is not to fi lter the data or format it any way. Its purpose
is strictly to communicate with the fi le. If you want to read the characters from the fi le in a
more useful manner than one character at a time, you can attach a high-level stream to the
low-level stream. For example, BufferedReader is a high-level stream that can be chained to
a FileReader and read in lines of characters at a time, converting the line of characters to a
String . The next section, “File Input and Output,” contains an example that demonstrates
this technique.
Search WWH ::




Custom Search