Saturday, 9 March 2013

Understanding I/O streams in Java


User input is required to make our programs more interactive and dynamic.For this it is essential to know what are Input and Output streams and how they work.

What are I/O streams in Java?

  • An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
  •  Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
  • No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data

Types of Streams in Java.

     A program uses an input stream to read data from a source, one item at a time:

A program uses an output stream to write data to a destination, one item at time:


   Streams can hold all sorts of data from primitive types to advanced objects.
   In next few posts we will go through various types of I/O streams like byte stream, character stream, object stream etc. Check for links in the Relates Links section at the bottom of this post.

The library defines four abstract classes that are the parents of all stream classes defined within the API:
  1. InputStream, 
  2. OutputStream, 
  3. Reader, and 
  4. Writer.

Above are classified into two sets of classes - InputStream/OuputStream and Reader/Writer. Difference being -
  • The stream classes are used for inputting and outputting all types of binary or byte data.
  • The reader and writer classes are used for inputting and outputting only character and String data.
NOTE : When wrapping a stream you can mix and match only types that inherit from the same abstract parent stream.
Eg. following combinations will not work -

new BufferedInputStream(new FileReader("data.txt")); // char stream inside byte stream
new BufferedWriter(new FileOutputStream("data.txt")); // byte stream inside char stream
new ObjectInputStream(new FileOutputStream("data.txt")); // input and output streams mixed

Note : The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a file, a network socket, or an array.

Related Links 

No comments:

Post a Comment

t> UA-39527780-1 back to top