Java Reference
In-Depth Information
Listing 7-33.
A Custom Java I/O Reader Class Named LowerCaseReader
// LowerCaseReader.java
package com.jdojo.io;
import java.io.Reader;
import java.io.FilterReader;
import java.io.IOException;
public class LowerCaseReader extends FilterReader{
public LowerCaseReader(Reader in) {
super(in);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int count = super.read(cbuf, off, len);
if (count != -1) {
// Convert all read characters to lowercase
int limit = off + count;
for (int i = off; i < limit; i++) {
cbuf[i] = Character.toLowerCase(cbuf[i]);
}
}
return count;
}
}
Listing 7-34 shows how to use your new class. It reads from the file
luci4.txt
. It reads the file twice: the first
time by using a
LowerCaseReader
object and the second time by wrapping a
LowerCaseReader
object inside a
BufferedReader
object. Note that while reading the
licu4.txt
file the second time, you are taking advantage of the
readLine()
method of the
BufferedReader
class. The test class throws an exception in the declaration of its
main()
method to keep the code readable. The
luci4.txt
file should exist in your current working directory. Otherwise, you
will get an error when you run the test program.
Listing 7-34.
Testing the Custom Reader Class, LowerCaseReader
// LowerCaseReaderTest.java
package com.jdojo.io;
import java.io.FileReader;
import java.io.BufferedReader;
public class LowerCaseReaderTest {
public static void main(String[] args) throws Exception {
String fileName = "luci4.txt";
LowerCaseReader lcr = new LowerCaseReader(new FileReader(fileName));
System.out.println("Reading luci4.txt using LowerCaseReader:");
int c = -1;
while ((c = lcr.read()) != -1) {
System.out.print((char) c);