Java Reference
In-Depth Information
Solution
Use a
StreamTokenizer
,
readLine()
, and a
StringTokenizer
; the
Scanner
class (see
Scanning Input with the Scanner Class
)
; regular expressions (
Chapter 4
)
; or one of several
third-party “parser generator” tools.
Discussion
Though you could, in theory, read a file one character at a time and analyze each character,
that is a pretty low-level approach. The
read()
method in the
Reader
class is defined to re-
turn
int
so that it can use the time-honored value
-1
(defined as EOF in Unix
<stdio.h>
for
years) to indicate that you have read to the end of the file:
src/main/java/io/ReadCharsOneAtATime.java
public
public class
class
ReadCharsOneAtATime
ReadCharsOneAtATime
{
void
void
doFile
(
Reader is
)
throws
throws
IOException
{
int
int
c
;
while
while
((
c
=
is
.
read
( )) != -
1
) {
System
.
out
.
print
((
char
char
)
c
);
}
}
}
The cast to
char
is interesting. The program compiles fine without it, but does not print cor-
rectly because
c
is declared as
int
(which it must be, to be able to compare against the end-
of-file value
-1
). For example, the integer value corresponding to capital A treated as an
int
prints as 65, whereas
(char)
prints the character
A
.
combination of
readLine()
and
StringTokenizer
provides a simple means of scanning a
file. Suppose you need to read a file in which each line consists of a name like
user@host.domain
, and you want to split the lines into users and host addresses. You could
use this:
public
public class
class
ScanStringTok
ScanStringTok
{
protected
protected
LineNumberReader is
;
public
public static
static
void
void
main
(
String
[]
av
)
throws
throws
IOException
{