HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java InputStreamReader

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces