Java Reference
In-Depth Information
The classes used to read and write these streams are all subclasses of
Reader
and
Writer
.
These should be used for all text input instead of dealing directly with byte streams.
Reading Text Files
FileReader
is the main class used when reading character streams from a file. This class
inherits from
InputStreamReader
, which reads a byte stream and converts the bytes into
integer values that represent Unicode characters.
15
A character input stream is associated with a file using the
FileReader(
String
)
con-
structor. The string indicates the file, and it can contain path folder references in addition
to a filename.
The following statement creates a new
FileReader
called
look
and associates it with a
text file called
index.txt
:
FileReader look = new FileReader(“index.txt”);
After you have a file reader, you can call the following methods on it to read characters
from the file:
read()
returns the next character on the stream as an integer.
n
read(
char[]
,
int
,
int
)
reads characters into the specified character array with
the indicated starting point and number of characters read.
n
The second method works like similar methods for the byte input stream classes. Instead
of returning the next character, it returns either the number of characters that were read
or
-1
if no characters were read before the end of the stream was reached.
The following method loads a text file using the
FileReader
object
text
and displays its
characters:
FileReader text = new FileReader(“readme.txt”);
int inByte;
do {
inByte = text.read();
if (inByte != -1)
System.out.print( (char)inByte );
} while (inByte != -1);
System.out.println(“”);
text.close();
Because a character stream's
read()
method returns an integer, you must cast this to a
character before displaying it, storing it in an array, or using it to form a string. Every
character has a numeric code that represents its position in the Unicode character set.
The integer read off the stream is this numeric code.