Java Reference
In-Depth Information
Custom Input/Output Streams
Can you have your own I/O classes? The answer is yes. How difficult is it to have your own I/O classes? It is not
that difficult if you understand the decorator pattern. Having your own I/O class is just a matter of adding a
concrete decorator class in the I/O class hierarchy. In this section, you will add a new reader class that is called
LowerCaseReader . It will read characters from a character-based stream and convert all characters to lowercase.
The LowerCaseReader class is a concrete decorator class in the Reader class family. It should inherit from the
FilterReader class. It needs to provide a constructor that will accept a Reader object.
public class LowerCaseReader extends FilterReader {
public LowerCaseReader(Reader in) {
// Code for the constructor goes here
}
// More code goes here
}
There are two versions of the read() method in the FilterReader class to read characters from a character-based
stream. You need to override just one version of the read() method as follows. All other versions of the read()
method delegate the reading job to this one.
public class LowerCaseReader extends FilterReader {
public LowerCaseReader(Reader in) {
// Code for the constructor goes here
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
// Code goes here
}
}
That is all it takes to have your own reader class. You can provide additional methods in your class, if needed.
For example, you may want to have a readLine() method that will read a line in lowercase. Alternatively, you
can also use the readLine() method of the BufferedReader class by wrapping an object of LowerCaseReader in a
BufferedReader object. Using the new class is the same as using any other reader class. You can wrap a concrete
reader component such as a FileReader or a concrete decorator such as a BufferedReader inside a LowerCaseReader
object. Alternatively, you can wrap a LowerCaseReader object inside any other concrete reader decorator such as a
BufferedReader .
the Reader class has four versions of the read() method. the read(), read(CharBuffer target) , and
read(char[] cbuf) methods call the read(char[] cbuf, int off, int len) methods. therefore, you need to override
only the read(char[] cbuf, int off, int len) methods to implement your LowerCaseReader class.
Tip
Listing 7-33 has the complete code for the new LowerCaseReader class.
 
 
Search WWH ::




Custom Search