Java InputStreamReader

The Java InputStreamReader class is often used to read characters from files (or network connections) where the bytes represents text. In this Java tutorial, we will learn about InputStreamReader class, its creation and initialization, and its methods which help in reading the data from the source.

1. InputStreamReader class

  • It acts as a bridge between the byte stream to character stream. Using InputStreamReader, we can read any file in bytes and convert the bytes into chararctes of the desired charset.
  • It is part of java.io package.
  • It extends the abstract class Reader.
  • It implements Closeable, AutoCloseable and Readable interfaces.
  • It provides methods for reading the characters from the Stream.

2. Creating an InputStreamReader

As mentioned earlier, InputStreamReader reads a file using byte stream and convert to character strea. It means we have to first create a InputStream and then use this Reader to read characters from the stream.

In given below example, InputStreamReader will read the characters from the input stream fis, that in turn reads the bytes from the file data.txt.

To set the Charset information is optional. In that case, the system’s default charset will be used.

String file = "c:\temp\data.txt";

// Creates an InputStream
FileInputStream fis = new FileInputStream(file);

// Creates an InputStreamReader
InputStreamReader isr = new InputStreamReader(fis);

3. Setting Character Encoding

If the read characters from stream are in a different encoding then pass the set the Charset information in InputStreamReader‘s constructor.

String file = "c:\temp\data.txt";

FileInputStream fis = new FileInputStream(file);

InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF8"));

4. Closing the InputStreamReader

Call the inputStreamReader.close() method when we are done with reading from the stream. Or we can use the auto-closable feature of this class.

In the given example, try-with-resources feature will close the InputStreamReader and FileInputStream automatically when the try block is completely executed.

String file = "c:\temp\data.txt";

try (InputStreamReader input 
		= new InputStreamReader(new FileInputStream(file))) {

	//Perform operations
}

5. Java InputStreamReader Example

Lets see a few examples to read a file using the InputStreamReader in Java. In each example, we will read the file demo.txt.

hello world 1
hello world 2
hello world 3

Example 1: Reading a file using InputStreamReader

In the given example, we are reading all the content of the file demo.txt into a character array. We then print the read characters into the standard output.

We should use this technique for small files. Also do not forget to create a sufficiently large character array that can store all the characters from the file.

The read(char[]) method reads characters into the given array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

import java.io.FileInputStream;
import java.io.InputStreamReader;

public class InputStreamReaderExample 
{
	public static void main(String[] args) 
	{
		// Creates an array of character
		char[] array = new char[50];

		try (InputStreamReader input 
				= new InputStreamReader(new FileInputStream("demo.txt"))) {

			// Reads characters from the file
			input.read(array);

			System.out.println(array);
		}

		catch (Exception e) {
			e.getStackTrace();
		}
	}
}

Program output:

hello world 1
hello world 2
hello world 3

Example 2: Java Read file char by char using InputStreamReader

In the given example, we will read the same file, but one character at a time. This can be used to read larger files as well.

import java.io.FileInputStream;
import java.io.InputStreamReader;

public class InputStreamReaderExample 
{
	public static void main(String[] args) 
	{
		try (InputStreamReader input 
				= new InputStreamReader(new FileInputStream("demo.txt"))) {

			int data = input.read();  

            while (data != -1) 
            {  
            	//Do something with data e.g. append to StringBuffer
                System.out.print((char) data);  
                data = input.read();  
            }  
		}
		catch (Exception e) {
			e.getStackTrace();
		}
	}
}

Program output:

hello world 1
hello world 2
hello world 3

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.