Input Stream Reader Example Java Program

Definition

The InputStreamReader class converts an InputStream to a Reader. It has constructors that support specifying the character encoding to use. This is used with FileInputStream.

Syntax

	FileInputStream Variable_name_1 = new FileInputStream("File_location");
	InputStreamReader Variable_name_2 = new InputStreamReader(Variable_name_1);

Input Stream Reader Example Program

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

public class InputStreamReaderExample {
	public static void main(String[] args) throws IOException {
		FileInputStream fistr = null;
		InputStreamReader istrr =null;
		char c;
		int i;
		try {
			fistr = new FileInputStream("C:/newfile.txt");// Assuming a text file newfile.txt with content "JAVA"
			istrr = new InputStreamReader(fistr);
			while((i=istrr.read())!=-1){
				c=(char)i;
				System.out.println("Character Read: "+c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(fistr!=null)
			fistr.close();
			if(istrr!=null)
            istrr.close();
		}   
	}
}

Sample Output

Output is:
Character Read:J
Character Read:A
Character Read:V
Character Read:A