Java.io.InputStreamReader.read() Method

Advertisements


Description

The java.io.InputStreamReader.read(char[] cbuf, int offset, int length) method reads character into a portion of an array.

Declaration

Following is the declaration for java.io.InputStreamReader.read(char[] cbuf, int offset, int length) method:

public int read(char[] cbuf, int offset, int length)

Parameters

  • cbuf -- Destination character buffer

  • offset -- Offset at which to start storing characters

  • length -- Maximum numbers of characters to read

Return Value

The method returns the number of characters read, else -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(char[] cbuf, int offset, int length) 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[] cbuf = new char[5];
      int i;
      
      try {
         // new input stream reader is created 
         fis = new FileInputStream("C:/test.txt");
         isr = new InputStreamReader(fis);
         
         // reads into the char buffer
         i = isr.read(cbuf, 2, 3);
         
         // prints the number of characters
         System.out.println("Number of characters read: "+i);
         
         // for each character in the character buffer
         for(char c:cbuf)
         {
            // for empty character
            if(((int)c)==0)
               c='-';
            
            // prints the characters
            System.out.println(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:

Number of characters read: 3
-
-
A
B
C



Advertisements
Advertisements