|
|
|
|||
|
How to Use Pipe StreamsPipedReaderPipedWriterPipedInputStreamPipedOutputStreamConsider a class that implements various string manipulation utilities such as sorting and reversing text. It would be nice if the output of one of these methods could be used as the input for another so that you could string a series of method calls together to perform some higher-order function. For example, you could reverse each word in a list, sort the words, and then reverse each word again to create a list of rhyming words. Without pipe streams, the program would have to store the results somewhere (such as in a file or in memory) between each step, as shown here: ![]() This figure has been reduced to fit on the page. Click the image to view it at its natural size. ![]() PipedReader and PipedWriter
to connect the input and output of its reverse
and sort methods in
order to create a list of rhyming words. Several classes make up this
program. This section shows and discusses only the elements of the
program that read from and write to the pipes. Follow the code
links presented here to see the whole program.
First, let's look at the calling sequence of the
The innermost call to reverse takes a
FileReader opened on the file
words.txt that
contains a list of words. The return value of reverse is
passed to sort, whose return value is then passed to
another call to reverse.
Let's look at the
The bold statements in reverse create both ends of a
pipe--a PipedWriter and a PipedReader--
and connects them by constructing
the PipedReader "on" the PipedWriter.
Whatever's written to the
PipedWriter can be read from the PipedReader.
The connection forms a
pipe, as illustrated here:
![]() reverse starts a
ReverseThread
that writes its output to the PipedWriter
and then returns the PipedReader to the caller.
The caller then arranges for a sorting thread to read from it.
The sort method is exactly the same,
except that it creates and starts a
SortThread.
Using Streams to Wrap Other StreamsThe
| |||
|