Java CharArrayReader read() Method
In this tutorial, we will learn about the read()
method of the CharArrayReader class in Java. This method is implemented to read a single character from the stream. The stream is blocked by this method till it takes some input from the stream or eventually it reaches the end of the stream, reading characters.
Syntax
No parameter is needed in this method and it returns the read character from the stream, in the form of an integer value, ranging from 0 to 65535, otherwise, it returns -1 if it reaches the end of the stream.
public int read() throws IOException
Example: Read Data using CharArrayReader Method
In this example, we are reading the data from the character array using the read()
method of CharArrayReader
class, when we read the data this method returns the ASCII
code in integer format so we have to typecast it to the character. We are iterating the loop 12 times because our character array contains 12 characters.
import java.io.CharArrayReader;
class StudyTonight
{
public static void main(String[] args)
{
try
{
char[] str = {'S', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't' };
CharArrayReader reader = new CharArrayReader(str);
int ch;
for (int i = 0; i < 12; i++)
{
ch = reader.read();
System.out.print(" "+ (char)ch);
}
reader.close();
}
catch (Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
S t u d y t o n i g h t
Example: Read Data using CharArrayReader Method
Here, we are reading the data from string but instead of reading to the console we copy it to the character buffer using another overloading method and then we print it. This method returns the number of characters copied.
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
class StudyTonight
{
public static void main(String[] args)
{
String s = "studytonight";
Reader reader = new StringReader(s);
char charBuffer[] = new char[12];
try
{
System.out.println(reader.read(charBuffer, 0, 12));
System.out.println(charBuffer);
reader.close();
}
catch (IOException e)
{
System.out.println("Error: "+e.toString());
}
}
}
12
studytonight
Conclusion
In this tutorial, we learned about the read()
method of the CharArrayReader class in Java, which is used to read a single character from the stream, which it returns as an integer value, ranging from 0 to 65535, or it returns -1 if the end of the stream is reached.