Friday, August 3, 2012

I/O Streams in Java – with simple example



       Streams are used to transfer data from one location to location, just like a water pipe which carrires water from one place to other.

Different sizes of waters pipes are used to carry water from different sources (Ex: Ground water, from water tank, from reservoir, etc.).  The size and type of the pipe depend upon the quantity of water that to be transferred.  Similarly in java different streams are used to transfer data to/from different source (Ex: input device, output device and files)
In java, basically there are two types of streams available
1.      Input Stream – A stream is used to read data from an input source is called Input Stream.
2.      Output Stream – A stream is used to read data to an output stream is called output stream.
All streams in java are represented by classes in “java.io” package. The java.io package contains serialization classes and the file system classes along with these stream classes. In java all Input and output operations are performed through these data streams.
Let us now consider, a simple example “reading a character from keyboard” to better understand the streams.

Import java.io.*;
Class KeyboardChar
{
            Public static void main (String arg[])
            {
 // CreateInputStreamReader and BufferedReaders object to accept data from keyboard
                        InputStreamReader  Istream  =  InputStreamReader(System.in);
                        BufferedReader br = new BufferedReader(Istream);
                        System.out.println(“Enter a character”);
                        Char ch = (char) br.read(); // read a single character
                        System.out.println(“You Entered : ” + ch);
            }

}

In the above program, System.in is representing a standard input device i.e, keyboard. Now this “System.in” is a source of data like Reservoir of water as shown in figure 1.1. Here the keyboard is a Input Stream object.
Figure 1.1 shows the data flow in Streams similar to water flow in a pipe 



The “InputReaderClass” is like a water pipe to carry data. Till now it is good, now what about the “Buffered Stream Reader” class? BufferedStreamReader class is like a water tap at end of the pipe which is used to control the water flow.
Therefore, Buffered Stream Reader is an efficient way to bring the data outside of the pipe by using different controls like
1.      br.read(); à slow
2.      br.readLine(); -- > fast



br.read() is used bring the data slowly like character by character (open the water tap slightly).
br.readLine() is used to bring the more data like entire line of data can be read (open the water tape completly).



0 comments :

Post a Comment

0 comments :

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger