Java.io.CharArrayReader.read() Method



Description

The java.io.CharArrayReader.read() method reads a single character. If the stream ends, it returns -1.

Declaration

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

public int read()

Parameters

NA

Return Value

The method returns the character read, as an integer from the range 0 to 65535. If the stream has reached it's end the read() returns -1.

Exception

IOException − If any I/O error occurs.

Example

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

package com.tutorialspoint;

import java.io.CharArrayReader;
import java.io.IOException;

public class CharArrayReaderDemo {
   public static void main(String[] args) {      CharArrayReader car = null;
      char[] ch = {'H', 'E', 'L', 'L', 'O'};
      
      try {
         // create new character array reader
         car = new CharArrayReader(ch);
         
         int value = 0;
         
         // read till the end of the file
         while((value = car.read())!=-1) {
            char c = (char)value;
            
            // print the character
            System.out.print(c+" : ");
            
            // print the integer
            System.out.println(value);
         }
         
      } catch(IOException e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(car!=null)
            car.close();
      }
   }
}

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

H : 72
E : 69
L : 76
L : 76
O : 79
java_io_chararrayreader.htm
Advertisements