Java InputStream Class


The InputStream class in Java is part of the java.io package and provides a fundamental way to read byte data from various sources like files, network connections, or memory buffers. It serves as the base class for many specialized input streams, making it a core part of Java's I/O (Input/Output) system.

Since InputStream deals with byte data, it is typically used for reading raw binary data such as images, audio files, or other non-text files. In this blog, we will explore the InputStream class, its key methods, and how it can be used to perform basic I/O operations in Java.


What is the InputStream Class?

The InputStream class is an abstract class that serves as the superclass for all classes representing byte input streams in Java. It provides a way to read raw byte data, and several classes extend it to handle more specific input sources like files, byte arrays, and network connections.

Some commonly used subclasses of InputStream include:

  • FileInputStream: Reads bytes from a file.
  • ByteArrayInputStream: Reads bytes from an array.
  • ObjectInputStream: Reads objects from a stream (used for deserialization).
  • BufferedInputStream: Provides buffered reading for performance improvement.

Key Methods of the InputStream Class

The InputStream class provides several methods for reading byte data. Below are some key methods of the InputStream class:

  1. int read():
    Reads the next byte of data from the input stream. Returns the byte read as an integer value, or -1 if the end of the stream is reached.

  2. int read(byte[] b):
    Reads up to b.length bytes of data into an array. Returns the number of bytes read, or -1 if the end of the stream is reached.

  3. long skip(long n):
    Skips n bytes of input. Returns the actual number of bytes skipped.

  4. int available():
    Returns the estimated number of bytes that can be read (or skipped) without blocking.

  5. void close():
    Closes the input stream and releases any system resources associated with it.

  6. boolean markSupported():
    Returns true if the stream supports the mark() and reset() methods. (Not all streams support this.)


Using the Java InputStream Class: Practical Examples

Example 1: Reading Data from a File Using FileInputStream

The FileInputStream class is a direct subclass of InputStream and is used to read byte data from a file. Here's an example of how to use it to read data from a file:

import java.io.*;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);  // Print each byte as a character
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • FileInputStream is used to open the file example.txt for reading.
  • The read() method is called in a loop to read one byte at a time.
  • The byte is then cast to a char and printed as a character.

Output:

This is the content of the example.txt file.

Example 2: Reading Data from a Byte Array Using ByteArrayInputStream

The ByteArrayInputStream class is another subclass of InputStream that allows you to read data from a byte array. Here's how you can use it:

import java.io.*;

public class ByteArrayInputStreamExample {
    public static void main(String[] args) {
        byte[] data = "Hello, Java InputStream!".getBytes();  // Convert string to byte array
        
        try (ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
            int content;
            while ((content = bais.read()) != -1) {
                System.out.print((char) content);  // Print each byte as a character
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the byte array.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • A byte array data is created by converting a string into bytes.
  • ByteArrayInputStream is used to read from the byte array.
  • The read() method is used to read each byte and convert it back into a character.

Output:

Hello, Java InputStream!

Example 3: Using the Available Method

The available() method returns an estimate of the number of bytes that can be read from the stream without blocking. Here’s an example:

import java.io.*;

public class AvailableMethodExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            System.out.println("Bytes available: " + fis.available());  // Get available bytes
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);  // Print each byte as a character
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • The available() method returns the number of bytes that can be read immediately without blocking.
  • Then, the read() method is used to read and display the content of the file.

Closing the InputStream

Always remember to close the stream after you are done using it. This ensures that any system resources (like file handles or network connections) are properly released. This can be done using the close() method, or more commonly with a try-with-resources statement, which automatically closes the stream when done.


Advantages of Using InputStream

  1. Flexibility: The InputStream class and its subclasses provide various ways to read data from different sources like files, byte arrays, or network streams.
  2. Efficiency: By reading raw bytes directly, InputStream is highly efficient for binary data and can be used for reading large files or network packets.
  3. Extensibility: The InputStream class is designed to be subclassed, which means you can create custom streams for specialized purposes if needed.