Java.io.Reader.read() Method

Advertisements


Description

The java.io.Reader.read(char[] cbuf) method reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Declaration

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

public int read(char[] cbuf)

Parameters

  • cbuf -- Destination buffer

Return Value

This method returns the number of characters read, or -1 if the end of the stream has been reached

Exception

  • IOException -- If the stream does not support mark(), or if some other I/O error occurs

Example

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

package com.tutorialspoint;

import java.io.*;

public class ReaderDemo {

   public static void main(String[] args) {

      String s = "Hello world";

      // create a StringReader
      Reader reader = new StringReader(s);

      // create a char array to read chars into
      char cbuf[] = new char[5];

      try {
         // read characters into an array.
         System.out.println("" + reader.read(cbuf));

         // print cbuf
         System.out.println(cbuf);

         // close the stream 
         reader.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

5
Hello



Advertisements
Advertisements