Java Reference
In-Depth Information
This approach to dealing with on-disk data can lack some flexibility—most develop‐
ers think in terms of characters, not bytes. To allow for this, the streams are usually
combined with the higher-level
Reader
and
Writer
classes, that provide a character-
stream level of interaction, rather than the low-level byte stream provided by
Input
Stream
and
OutputStream
and their subclasses.
Readers and Writers
By moving to an abstraction that deals in characters, rather than bytes, developers
are presented with an API that is much more familiar, and that hides many of the
issues with character encoding, Unicode, and so on.
The
Reader
and
Writer
classes are intended to overlay the byte stream classes, and
to remove the need for low-level handling of I/O streams. They have several sub‐
classes that are often used to layer on top of each other, such as:
•
FileReader
•
BufferedReader
•
InputStreamReader
•
FileWriter
•
PrintWriter
•
BufferedWriter
To read all lines in from a file, and print them out, we use a
BufferedReader
layered
on top of a
FileReader
, like this:
try
(
BufferedReader
in
=
new
BufferedReader
(
new
FileReader
(
filename
)))
{
String
line
;
while
((
line
=
in
.
readLine
())
!=
null
)
{
System
.
out
.
println
(
line
);
}
}
catch
(
IOException
e
)
{
// Handle FileNotFoundException, etc. here
}
If we need to read in lines from the console, rather than a file, we will usually use an
InputStreamReader
applied to
System.in
. Let's look at an example where we want
to read in lines of input from the console, but treat input lines that start with a spe‐
cial character as special—commands (“metas”) to be processed, rather than regular
text. This is a common feature of many chat programs, including IRC. We'll use
regular expressions from
Chapter 9
to help us:
Pattern
SHELL_META_START
=
Pattern
.
compile
(
"^#(\\w+)\\s*(\\w+)?"
);
try
(
BufferedReader
console
=
new
BufferedReader
(
new
InputStreamReader
(
System
.
in
)))
{