Java.io.InputStreamReader.read() Method

Advertisements


Description

The java.io.InputStreamReader.read() method reads and return a single character.

Declaration

Following is the declaration for java.io.InputStreamReader.read() method:

public int read()

Parameters

  • NA

Return Value

The method returns the character read, or -1 if the end of the stream has been reached.

Exception

  • IOException -- If an I/O error occurs

Example

The following example shows the usage of java.io.InputStreamReader.read() method.

package com.tutorialspoint;

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

public class InputStreamReaderDemo {
   public static void main(String[] args) throws IOException {
      FileInputStream fis = null;
      InputStreamReader isr =null;
      char c;
      int i;
      
      try {
         // new input stream reader is created 
         fis = new FileInputStream("C:/test.txt");
         isr = new InputStreamReader(fis);
         
         // read till the end of the file
         while((i=isr.read())!=-1)
         {
            // int to character
            c=(char)i;
            
            // print char
            System.out.println("Character Read: "+c);
         }
      } catch (Exception e) {
      
         // print error
         e.printStackTrace();
      } finally {
         
         // closes the stream and releases resources associated
         if(fis!=null)
            fis.close();
         if(isr!=null)
            isr.close();
      }   
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE

Let us compile and run the above program, this will produce the following result:

Character Read: A
Character Read: B
Character Read: C
Character Read: D
Character Read: E



Advertisements
Advertisements