Tuesday, May 10, 2011

Working with Filtered Streams

You attach a filtered stream to another stream to filter the data as it's read from or written to the original stream. The java.io package contains these filtered streams which are subclasses of either FilterInputStream(in the API reference documentation) or FilterOutputStream(in the API reference documentation):

  • DataInputStream and DataOutputStream
  • BufferedInputStream and BufferedOutputStream
  • LineNumberInputStream
  • PushbackInputStream
  • PrintStream (this is an output stream)
This section shows you how to use filtered streams through an example that uses a DataInputStream and a DataOutputStream. In addition, this section shows you how to write your own filtered streams.
Using Filtered Streams
To use a filtered input or output stream, attach the filtered stream to another input or output stream. For example, you can attach a DataInputStream to the standard input stream as in the following code:
DataInputStream dis = new DataInputStream(System.in);
String input;

while ((input = dis.readLine()) != null) {
. . . // do something interesting here
}
You might do this so that you can use the more convenient readXXX methods, such as readLine, implemented by DataInputStream.

No comments:

Post a Comment

Chitika