Java.io.FilterReader.read() Method



Description

The java.io.FilterReader.read(char[] cbuf, int off, int len) method reads character of length len into the array, starting at offset off.

Declaration

Following is the declaration for java.io.FilterReader.read(char[] cbuf, int off, int len) method −

public int read(char[] cbuf, int off, int len)

Parameters

  • cbuf − Destination buffer.

  • off − Offset at which to start storing characters.

  • len − Number of characters to read.

Return Value

This method returns the number of characters to read, or -1 if the end of the stream is reached.

Exception

IOException − If an I/O error occurs.

Example

The following example shows the usage of java.io.FilterReader.read(char[] cbuf, int off, int len) method.

package com.tutorialspoint;

import java.io.FilterReader;
import java.io.Reader;
import java.io.StringReader;

public class FilterReaderDemo {
   public static void main(String[] args) throws Exception {
      FilterReader fr = null;
      Reader r = null;
      char[] cbuf = new char[6];
      int i = 0;
      
      try {
         // create new reader
         r = new StringReader("ABCDEF");
          
         // create new filter reader
         fr = new FilterReader(r) {
         };
         
         // read data of len 4, to the buffer
         i = fr.read(cbuf, 2, 4);
         System.out.println("No. of characters read: "+i);
         
         // read till the end of the char buffer
         for(char c:cbuf) {
         
            // checks for the empty character in buffer
            if((byte)c == 0)
               c = '-';
            
            // prints
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases system resources associated with this stream
         if(r!=null)
            r.close();
         if(fr!=null)
            fr.close();
      }
   }
}

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

No. of characters read: 4
--ABCD
java_io_filterreader.htm
Advertisements