Java InputStreamReader Class


The InputStreamReader class in Java is a bridge between byte-based input streams (like InputStream) and character-based input streams (like Reader). This class allows you to read bytes from an input stream and decode them into characters using a specified character encoding. It is a subclass of the Reader class and is typically used when you want to read data from an input stream (such as a file or network connection) and convert it into text data.

The InputStreamReader class is particularly useful when working with files or data sources that store text in a specific encoding (such as UTF-8, ISO-8859-1, etc.) and you need to convert the raw byte data into characters.


What is the Java InputStreamReader Class?

The InputStreamReader class in Java is used to read bytes from an InputStream and convert them into characters using a specified charset (character encoding). It is a subclass of the Reader class and acts as a bridge between byte-based input streams and character-based streams.

Key features of the InputStreamReader class include:

  1. Byte-to-Character Conversion: It reads bytes from an input stream and converts them into characters according to the specified encoding.
  2. Character Encoding Support: By default, InputStreamReader uses the platform’s default character encoding, but you can specify a different encoding.
  3. Efficient Character Handling: It provides an easy way to convert byte data (from files or network) into readable character data, making it ideal for text files and network communication.

Constructor of the InputStreamReader Class

The InputStreamReader class provides two primary constructors:

  1. InputStreamReader(InputStream in):
    This constructor creates an InputStreamReader that reads from the provided InputStream using the platform’s default character encoding.

    InputStreamReader reader = new InputStreamReader(System.in);
    
  2. InputStreamReader(InputStream in, String charsetName):
    This constructor allows you to specify a character encoding (e.g., "UTF-8", "ISO-8859-1", etc.) for decoding the byte data into characters.
    InputStreamReader reader = new InputStreamReader(System.in, "UTF-8");
    

Key Methods of the InputStreamReader Class

The InputStreamReader class inherits several methods from the Reader class. Some of the most important methods are:

  1. int read():
    Reads a single character of data from the input stream and returns it as an integer. It returns -1 if the end of the stream is reached.

    int data = reader.read();
    
  2. int read(char[] cbuf):
    Reads a block of characters into the provided character array. This method returns the number of characters read or -1 if the end of the stream is reached.
    char[] buffer = new char[1024];
    int numChars = reader.read(buffer);
    
  3. long skip(long n):
    Skips n characters in the input stream. This method returns the actual number of characters skipped.
    long skippedChars = reader.skip(100);
    
  4. boolean ready():
    Tests whether the InputStreamReader is ready to be read. This method returns true if the reader is ready to supply data.
    if (reader.ready()) {
        System.out.println("Ready to read data.");
    }
    
  5. void close():
    Closes the InputStreamReader, releasing any resources associated with it. Always call close() when done to free resources.
    reader.close();
    

Using the Java InputStreamReader Class: Practical Examples

Example 1: Reading Data from the Console Using InputStreamReader

In this example, we use InputStreamReader to read input from the console (System.in), which is a byte stream, and convert it into character data.

import java.io.*;

public class InputStreamReaderExample {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter some text:");

        // Create InputStreamReader to read from the console
        InputStreamReader reader = new InputStreamReader(System.in);
        
        // Read a single character from the console
        int data = reader.read();
        
        // Print the character (as a character)
        System.out.println("You entered: " + (char) data);
        
        reader.close();
    }
}

Explanation:

  • We create an InputStreamReader to read from System.in, which is an input stream for reading user input from the console.
  • The read() method reads a single character from the console and prints it.
  • We close the reader at the end to release resources.

Sample Output:

Enter some text:
H
You entered: H

Example 2: Reading Data from a File Using InputStreamReader

This example shows how to use InputStreamReader to read data from a file.

import java.io.*;

public class FileInputStreamReaderExample {
    public static void main(String[] args) throws IOException {
        // Create an InputStreamReader to read a file
        InputStreamReader reader = new InputStreamReader(new FileInputStream("example.txt"));
        
        // Read characters from the file
        int data = reader.read();
        while (data != -1) {
            System.out.print((char) data);
            data = reader.read();
        }

        reader.close();
    }
}

Explanation:

  • We create an InputStreamReader object that reads from the file example.txt (a byte stream).
  • The read() method is used to read data character by character and print it.
  • After reading the file, we close the reader to release resources.

Sample Output (assuming example.txt contains "Hello, World!"):

Hello, World!

Example 3: Using InputStreamReader with a Specific Charset

In this example, we read data from a file using a specific character encoding (UTF-8).

import java.io.*;

public class InputStreamReaderWithCharsetExample {
    public static void main(String[] args) throws IOException {
        // Create an InputStreamReader with UTF-8 encoding
        InputStreamReader reader = new InputStreamReader(new FileInputStream("example.txt"), "UTF-8");
        
        // Read characters from the file
        int data = reader.read();
        while (data != -1) {
            System.out.print((char) data);
            data = reader.read();
        }

        reader.close();
    }
}

Explanation:

  • The InputStreamReader is created with the UTF-8 character encoding, which is used to decode bytes read from the file into characters.
  • The rest of the code works similarly to the previous example, reading and printing characters from the file.

Advantages of Using the Java InputStreamReader Class

  1. Character Encoding Support: You can specify the character encoding (such as UTF-8, ISO-8859-1), ensuring correct handling of characters from different languages and formats.
  2. Efficient Byte-to-Character Conversion: The InputStreamReader allows for easy conversion of byte data to character data, making it ideal for working with text files and other character-based data sources.
  3. Compatibility: It is compatible with byte-based streams (such as FileInputStream or Socket) and can be used to read data from any source that provides an input stream.