Course Content‎ > ‎Session 6‎ > ‎

Byte Stream - InputStream

In java.io package, there are two abstract classes InputStream and OutputStream. All specialized input and output operations for byte streams are derived from these two classes.

InputStream

InputStream provides several methods for basic input needs. Input can be received from various sources like:  
    1.  A file
    2.  A String object
    3.  An array of bytes
    4.  A sequence of streams, which can be put together into a single stream


                 Hierarchy for InputStream class

All specialized classes, which deal with input of byte streams, are inherited from InputStream. By inheritance, all classes derived from the InputStream have a basic method called read(), which can be used for reading a single byte or an array of bytes. close() is used to close the InputStream. Given below is a table, which gives the syntax of these methods:


Method                   Description                                                                                              
int read()               Reads a single byte of data from the stream.  
                         Return value = byte read or -1 (for  end of the stream).
int read(byte [ ])       Reads data into an array of bytes. 
                         Return value = bytes read or -1 (for the end of the stream)
int read(byte [ ], int)  Reads data into an array of bytes starting at a specific
                         location in the array.
close()                  Closes the input stream and releases any resources 
                         allocated by the stream

Types of InputStream   

There can be different InputStream classes, based on the source of the input.

FileInputStream  
FileInputStream is an InputStream, which provides basic input capabilities for dealing with files.  For reading the information from a file, a FileInputStream object has to be created, using one of the three constructors that accept the name of file, a file object or a FileDescriptor object respectively.

Given below is an example that prints the contents of a binary file named as demo.class to the console.

    //A program showing how to read a binary file
    
    import java.io.*;
    class ReadFile
    {
        public static void main(String args[])
        {
            try
            {
                //fis is a FileInputStream object
                FileInputStream fis=new FileInputStream("demo.class");  
                
                while (fis.available() > 0)   
                    // read the file demo.class until the EOF; available method  
                    // returns the no. of bytes read, without blocking  
                {
                    System.out.print((char)fis.read());  //reads one byte at a time
                }
            }
            catch(IOException e)
            {
                System.out.println("Error reading file "+e);
            }
        }
    }

Output of the above code, upon execution will show the output in the computer language, since it is a binary file. In the above code, a FileInputStream object fis is created, using the constructor FileInputStream (which takes one argument, that is, the binary file name demo.class)

The available() method is used to return the number of bytes read, without blocking. Until the number of bytes read is greater than zero, each byte is read and printed on the screen. There is a try-catch block to catch any IOException, which might be raised, when reading the file.

FilterInputStream  
Filter streams provide the capability to manipulate the data as it passes through a stream. It can also be chained together to create a combined effect of several filters.  FilterInputStream is the base class for all the input stream filters. This class does not make any modifications to the attached stream, but provides the chaining functionality, which is used by its sub classes. The FilterInputStream is attached to an input stream, by passing the input stream to the constructor of the filter stream. FilterInputStream can be used to read primitive data as well as String objects, using DataInputStream class. It has BufferedInputStream, which can be used to prevent a physical read, when you want more data.

DataInputStream is used in conjunction with DataOutputStream. (Code example for DataInputStream is given below with the DataOutputStream). DataInputStream implements the DataInput interface. The methods for DataInputStream start with the read, such as readInt(), readDouble(), readChar(), readByte(), readLong(), readFloat(), readBoolean(), readLine(). 

BufferedInputStream
This provides its attached stream a buffer or cache. This helps in increasing the performance of some input streams, especially those bound to slower sources like network connection. You can either specify the size of the buffer used by BufferedInputStream, when it is created or accept the default of 2048 bytes.  Anytime a read request is satisfied from the buffer, you have potentially saved a slow read from the attached stream.  

Given below is an example, which uses BufferedInputStream to read a file:  

    //Reading from the buffer stream
    import java.io.*;
    public class buffer
    {
        public static void main(String args[])
        {
            try
            {
                /* create and attach a simple file input stream to a buffered
                   filter, using the default buffer size of 2048 bytes */
                BufferedInputStream bis = 
                   new BufferedInputStream(new FileInputStream("demo.class"));
                
                // read the buffered stream 
                while(bis.available() > 0)  
                {
                    System.out.print((char)bis.read());
                }
            }
            catch(IOException e)
            {
                System.err.println("Error reading file" +e);
            }
        }
    }

In the above example, when the first call to read() is made, the BufferedInputStream reads in 2048 bytes,  and simply returns one byte at a time from the buffer for subsequent reads.
 
It is always going to be faster to satisfy a read request from a memory location within the program, than it is to make a system
call to the operating system.

LineNumberInputStream
This class was used to count the number of lines that have been read. It has been deprecated, since JDK 1.1

ByteArrayInputStream  
This class allows an application to create an input stream in which the bytes read are supplied by the contents of a byte array.

SequenceInputStream
This class can be used to convert two or more InputStream objects into a single InputStream. Here is an example showing the use of this stream:

    /* A program to show, how the contents of two files can be concatenated, 
       using SequenceInputStream */
    
    import java.io.*;
    public class sequence
    {
        public static void main(String [] args)
        {
            try
            {
                FileInputStream fis1 = new FileInputStream("demo.class");
                FileInputStream fis2 = new FileInputStream("demo1.txt");
                SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
                
                int c;
                while ((c = sis.read()) != -1)
                {
                    System.out.write(c);
                }
                sis.close();
            }
            catch (Exception e)
            {
                System.out.println("Exception: "+e);
            }
        }
    }

In this code, demo.class is a binary file, whereas Demo.txt1 is a text file with the following data:

    What is your name?
    Here is your first lab.

In this example,
  • There are two FileInputStream objects created, using the FileInputStream constructor (which takes one argument i.e. the filename).
  • A new object SequenceInputStream takes two arguments the first and the second FileInputStrea. Until the end of the file is reached (when the output of read() is -1), one character at a time from both the files is written to the console.

Output of the above code, upon execution will be:

    ....Some binary data....
    What is your name?
    Here is your first lab.  

Comments