Sunday 29 July 2012

Concept of Streams

Abstraction of streams are used by java's I/O libraries.
Stream mainly represents any object that is capable of producing or receiving pieces of data.
There are lots of different devices (files, memory, network..etc) and there are different ways to talk to these devies (sequential, random access..). However streams makes this task easy by acting in the same way for every device.
There is no difference when we read from a network or from a local file or even from user's typing.
We need to import java.io package to use stream.

Based on functionality streams can be categorized as Node Stream and Filter Stream.

Node Streams are those which connect directly with the data source or destination and provide basic functionality for reading or writing data from that source or destination.
      FileReader fr = new FileReader(“input.txt”);
As we can see that FileReader is taking a data source “input.txt” as its argument and hence it is a node stream.

FilterStreams sit on top of a node stream and provide additional functionalities such as compression, security etc. FilterStreams take other
stream as their input.
      BufferedReader bf = new BufferedReader(fr);
BufferedReader enhances the functionality by buffering the input before delivering. Here BufferedReader is sitting on top of a node stream which is FileReader..



Based on data, streams can either be byte oriented or character oriented:

Classes which contain the word stream in their name are byte oriented and are used to read or write data in the form of bytes. eg: FileInputStream.

Classes which contain the word Reader/Writer are character oriented and read or write data in the form of characters. eg: FileReader.

Consider the below example which reads data from a file:


           FileReader fr = null;
      BufferedReader br = null;
    try {
       // attaching node stream with data source
       fr = new FileReader(“input.txt”);
       // attatching filter stream over node stream
       br = new BufferedReader(fr);
       String line = br.readLine();
       // printing and reading remaining lines
       while (line != null){
           System.out.println(line);
           line = br.readLine();
       }
       br.close();
       fr.close();
    }catch(IOException ioex){
       System.out.println(ioex);
    }

Similarly we can use FileWriter as a node stream and PrintWriter as filter stream for writing data to a file.


No comments:

Post a Comment