Java StringReader
StringReader
is a class in Java that allows you to read character streams from a string. It is a subclass of the Reader
class and is often used when you need to read data from a string as if it were a character stream.
Here's an example of how to use StringReader
to read a string as a character stream:
String data = "Hello, world!"; StringReader reader = new StringReader(data); int character; while ((character = reader.read()) != -1) { System.out.print((char) character); } reader.close();Sour.www:ectheitroad.com
In this example, we create a new StringReader
object and pass it the string "Hello, world!". We then use a while loop and the read()
method to read each character from the string and print it to the console. Note that we cast the character to a char
before printing it. Finally, we close the StringReader
using the close()
method.
The StringReader
class provides several methods that can be used to read from the character stream:
read()
: This method reads a single character from the stream and returns it as an integer value.read(char[] cbuf, int off, int len)
: This method reads characters from the stream into an array, starting at the specifiedoff
offset and reading up tolen
characters.skip(long n)
: This method skipsn
characters in the stream and returns the number of characters actually skipped.ready()
: This method returnstrue
if the stream is ready to be read, orfalse
otherwise.mark(int readAheadLimit)
: This method marks the current position in the stream, so that it can be returned to later using thereset()
method.reset()
: This method returns the stream to the position that was marked using themark()
method.close()
: This method closes the stream and releases any system resources associated with it.
Note that many of these methods can throw an IOException
if there is an error while reading from the stream. Therefore, it is important to handle exceptions appropriately when using these methods.