Java Reference
In-Depth Information
The following shows an input filter that converts characters to upper-
case:
public class UppercaseConvertor extends FilterReader {
public UppercaseConvertor(Reader in) {
super(in);
}
public int read() throws IOException {
int c = super.read();
return (c == -1 ? c :
Character.toUpperCase((char)c));
}
public int read(char[] buf, int offset, int count)
throws IOException
{
int nread = super.read(buf, offset, count);
int last = offset + nread;
for (int i = offset; i < last; i++)
buf[i] = Character.toUpperCase(buf[i]);
return nread;
}
}
We override each of the
read
methods to perform the actual read and
then convert the characters to upper case. The actual reading is done by
invoking an appropriate superclass method. Note that we don't invoke
read
on the stream
in
itselfthis would bypass any filtering performed
by our superclass. Note also that we have to watch for the end of the
stream. In the case of the no-arg
read
this means an explicit test, but
in the array version of
read
, a return value of 1 will prevent the
for
loop
from executing. In the array version of
read
we also have to be careful
to convert to uppercase only those characters that we stored in the buf-
fer.