Advertisement



< Prev
Next >



CharArrayReader



CharArrayReader class is a subclass of Reader abstract class and it is used to read a character or characters from its own buffer which is initialized using a character array.




Constructor :


CharacterArrayReader(char[] buf)
This constructor is most used and it creates a CharacterArrayReader object with its own buffer initialized to the value of a char array buf
Example-:
char[] arr= new char[]{'a','b','c','d','e','f'};
CharArrayReader car= new CharArrayReader(arr);
We have created a CharArrayReader object with its own buffer initialized to the value of a char array, arr.




Methods for reading CharArrayReader


Some methods that we generally use while working with CharArrayReader are shown in the table below :

Methods Description
available()
This method gives the remaining number of bytes available to read from this character input stream's buffer.

read()
This method reads one character at a time from this character input stream's buffer.

read(char[])
This method reads a whole character array at a time from this character input stream's buffer.

close()
This method closes this input stream and also frees any resources connected with this character input stream.




Advertisement




Reading a character using read() method of CharArrayReader class.


Here, we have initialized internal buffer of CharArrayReader to the value of char array.
//Program to use a character buffer that can be used as character input stream



import java.io.*;

class A
{
public static void main(String... ar)
{
char[] arr= new char[]{'a','b','c','d','e','f'};
CharArrayReader car= new CharArrayReader(arr); // an internet character buffer is created, 
					       //big enough to hold a character array
int c;
try
{
while( (c= car.read())!=-1) //buffer is read one character a time
System.out.print((char)c);
}
catch(IOException e)
{
System.out.println(e);
}

}
}



Output is


abcde


Program Analysis






Note

Even after closing the stream by calling close(), we can still read the characters out of buffer of CharArrayReader and no IOException will be thrown because data is already transferred to the buffer and it can be read even after stream is closed.



Please share this article -





< Prev
Next >
< OutputStreamWriter
CharacterArrayWriter >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement