Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java InputStreamReader read() method

In this tutorial, we will learn about the read() method of the InputStreamReader class in Java. This method is used to read and return a single character from the current stream. It is a non-static method, available in the java.io package, and can only be accessed using class objects.

Syntax

Following is the syntax declaration of this method. It does not accept any parameter and returns the actual character read, or -1 if the end of the stream is reached.

public int read()

Example 1: Read Character in InputStreamReader

In the following example, we are implementing InputStreamReader to read the data from a file. Firstly we created an input stream using FileInputStream class by passing a file path in a constructor. Then using the read() method we are reading each character one by one till the stream reaches the end. It returns -1 when we reach the end of the stream.

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try  {  
			InputStream stream = new FileInputStream("E:\\studytonight\\output.txt");  
			Reader reader = new InputStreamReader(stream);  
			int data = reader.read();  
			while (data != -1) {  
				System.out.print((char) data);  
				data = reader.read();  
			}  
		} catch (Exception e) {  
			System.out.print("Error: "+e.toString());
		}  
	}
}

Hello Studytonight

output.txt

Hello Studytonight

Example 1: Read Character in InputStreamReader

In this example, we read the data from the stream and copy it to the array then we will print that data. This method read and return a single character from the current stream.

import java.io.FileInputStream;
import java.io.InputStreamReader;
public class StudyTonight 
{
	public static void main(String[] args) 
	{		
		try
		{
			char[] array = new char[50];
			FileInputStream fileStream = new FileInputStream("E://studytonight//output.txt");
			InputStreamReader input = new InputStreamReader(fileStream);
			input.read(array); 
			System.out.println(array);
		}
		catch (Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	}
}


1
2
3

output.txt

1
2
3

Conclusion

In this tutorial, we learned about the read() method of the InputStreamReader class in Java, which reads and returns a single character, from the current stream, or -1, if it reaches the end of stream reading characters.