Description

On this document we will be showing a java example on how to use the read() method of InputStreamReader Class. This method reads a single character.

Overrides:

  • read in class Reader

Throws:

  • IOException – If an I/O error occurs

Method Syntax

public int read()
throws IOException

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns boolean, true if and only if the operation succeeded; false otherwise.

Compatibility

Requires Java 1.2 and up

Java InputStreamReader read() Example

Below is a java code demonstrates the use of read() method of InputStreamReader class. The example presented might be simple however it shows the behaviour of the read() method of InputStreamReader class.

package com.javatutorialhq.java.examples;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * This example source code demonstrates the use of  
 * read() method of InputStreamReader class
 */

public class InputStreamReaderReadExample {

	public static void main(String[] args) {		
		
		try {
			// initialize an input stream which in this case
			// we are intended to read a file thus 
			// FileInputStream object suits it best
			FileInputStream fis = new FileInputStream("C:javatutorialhq"
					+ "inputtest_file.txt");
			
			// initialize InputStreamReader object
			InputStreamReader is = new InputStreamReader(fis);
			
			// initialize variables
			int val; //character place holder
			String result=""; //result will accumulate on this variable
			
			while((val=is.read())!=-1){
				// concatenate the characters read from the stream
				result = result+(char)val; // note the conversion of int to char
			}
			// print the result read from the file
			System.out.println(result);
			is.close();
			fis.close();
		} catch (FileNotFoundException e) {
			System.out.println("File does not exists");
		} catch (IOException e) {
			System.out.println("IOException occured");
		}		
		

	}

}

Sample Output

Below is the sample output when you run the above example.

java lang InputStreamReader read() example output