Chaining streams together

To allow the creation of complex I/O processing Java uses the concept of "chaining" streams. This means that an instance of one Stream is passed as a parameter to the constructor of another. You can see this in action in the following example.

import java.io.*;
public class Stio {

public static void main(String argv[]){
      try{
      File f = new File("Output.txt");
      FileOutputStream fos= new FileOutputStream(f);
      OutputStreamWriter out = new OutputStreamWriter(fos);
      out.write("Hello World");
      out.close();
      }catch(Exception e){}
    }
}

The FileOutputStream class deals with the actual business of opening a file for writing and the OutputStreamWriter deals writing to the file. The OutputStreamWriter class was added with the JDK 1.1 and can take a constructor that takes a String to allow for handling character sets apart from the current default. This way you can process files that contain Unicode character sets such as Chinese or Cyrilic. The writer classes understand the idea of data as text rather than simply as a sequence of bytes that might be numbers or anything at all.

Note that the File class is a bit misleading as you might expect it exclusively refer to an actual file and to be concerned with writing to and from a physical file. By using Stream chaining you can assemble file processing functionality from multiple classes, rather than needing a huge range of discreet file processing classes.

Last modified: Sunday, 20 September 2015, 07:21 PM