Java - CharArrayReader read(char[] b, int off, int len) method



Description

The Java CharArrayReader read(char[] b, int off, int len) method reads characters into a specified portion of a character array. It attempts to read up to len characters and stores them in buf starting at index off. If fewer characters are available, it reads only those. If the end of the stream is reached, it returns -1.

Declaration

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

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

Parameters

  • b − destination array.

  • off − Offset to start storing characters.

  • len − number of characters to read.

Return Value

The actual number of characters read, -1 for the end of the stream.

Exception

IOException − If any I/O error occurs.

Example - Using CharArrayReader read(char[] b, int off, int len) method

The following example shows the usage of Java CharArrayReader read(char[] b, int off, int len) method.

CharArrayReaderDemo.java

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'};
      char[] d = new char[5];
      
      try {
         // create new character array reader
         car = new CharArrayReader(ch);
         
         // read character to the destination buffer
         car.read(d, 3, 2);
         
         // for every character in the buffer
         for (char c : d) {
            int i = (int)c;
            
            if(i == 0) {
               System.out.println("0");
            } else {
               System.out.println(c);
            }
            
         }
      } catch(IOException e) {
         // if I/O error occurs
         System.out.print("Stream is already closed");
      } finally {
         // releases any system resources associated with the stream
         if(car!=null)
            car.close();
      }
   }
}

Output

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

0
0
0
H
E

Example - Reading in Chunks and Printing Output

The following example shows the usage of Java CharArrayReader read(char[] b, int off, int len) method.

CharArrayReaderDemo.java

package com.tutorialspoint;

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

public class CharArrayReaderDemo {
   public static void main(String[] args) {
      char[] data = "Hello, CharArrayReader!".toCharArray();
      char[] buffer = new char[10]; // Buffer to store read characters

      try (CharArrayReader reader = new CharArrayReader(data)) {
         int charsRead;

         System.out.println("Reading characters in chunks:");
         while ((charsRead = reader.read(buffer, 0, buffer.length)) != -1) {
            System.out.print(new String(buffer, 0, charsRead)); // Convert read characters to String
         }
      } catch (IOException e) {
         System.err.println("IOException occurred: " + e.getMessage());
      }
   }
}

Output

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

Reading characters in chunks:
Hello, CharArrayReader!

Explanation

  • Initialize the Reader− The string "Hello, CharArrayReader!" is converted into a character array and passed to the CharArrayReader constructor.

  • Create a Buffer− A char[] buffer of size 10 is used to store chunks of characters.

  • Read Characters in Chunks

    • The read(buffer, 0, buffer.length) method reads up to 10 characters at a time.

    • The loop continues until the method returns -1 (end of stream).

  • Convert and Print− The read characters are converted into a String and printed.

Example - Reading a Specific Portion of Data into an Offset

The following example shows the usage of Java CharArrayReader read(char[] b, int off, int len) method.

CharArrayReaderDemo.java

package com.tutorialspoint;

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

public class CharArrayReaderDemo {
   public static void main(String[] args) {
      char[] data = "JavaProgrammingLanguage".toCharArray();
      char[] buffer = new char[15]; // Buffer size is larger than read length

      try (CharArrayReader reader = new CharArrayReader(data)) {
         // Read 10 characters starting at index 5 in buffer
         int charsRead = reader.read(buffer, 5, 10); 

         System.out.println("Buffer content after read operation:");
         for (char c : buffer) {
            System.out.print(c == '\0' ? '-' : c); // Print '-' for empty buffer spaces
         }
      } catch (IOException e) {
         System.err.println("IOException occurred: " + e.getMessage());
      }
   }
}

Output

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

Buffer content after read operation:
-----JavaProgra

Explanation

  • Initialize the Reader: "JavaProgrammingLanguage" is converted into a character array.

  • Create a Larger Buffer: The buffer size (15) is larger than the characters being read (10), leaving empty spaces.

  • Use an Offset in Reading:

    • The read(buffer, 5, 10) method reads 10 characters and stores them in buffer starting from index 5.

    • Indices 0-4 in the buffer remain unmodified.

  • Print with Indication: Uninitialized characters are printed as - for clarity.

Key Points

  • Controlled Reading

    • read(char[] buf, int off, int len) allows reading only a specified number of characters into a part of the buffer.

    • The buffer can be reused, avoiding excessive memory allocations.

  • Efficient Processing

    • Instead of reading one character at a time, batch processing improves performance.

  • Handling Partial Reads

    • If fewer than len characters remain, only the available characters are read.

    • If off + len exceeds the buffer size, an IndexOutOfBoundsException occurs.

  • Use Cases

    • Useful in file reading, data processing, or handling large text efficiently.

java_io_chararrayreader.htm