Java Reference
In-Depth Information
the InputStream class uses the single-byte read method as its fundament-
al reading method. In the Reader class subclasses must implement the
abstract close method in contrast to inheriting an empty implementa-
tionmany stream classes will at least need to track whether or not they
have been closed and so close will usually need to be overridden. Fin-
ally, where InputStream had an available method to tell you how much
data was available to read, Reader simply has a ready method that tells
you if there is any data.
As an example, the following program counts the number of whitespace
characters in a character stream:
import java.io.*;
class CountSpace {
public static void main(String[] args)
throws IOException
{
Reader in;
if (args.length == 0)
in = new InputStreamReader(System.in);
else
in = new FileReader(args[0]);
int ch;
int total;
int spaces = 0;
for (total = 0; (ch = in.read()) != -1; total++) {
if (Character.isWhitespace((char) ch))
spaces++;
}
System.out.println(total + " chars, "
+ spaces + " spaces");
}
}
This program takes a filename from the command line. The variable
in represents the character stream. If a filename is not provided, the
 
Search WWH ::




Custom Search