In this section we will discuss about the StringReader class in Java.
StringReader class reads the string from the input stream. This class extends the java.io.Reader. Source for this character stream is a string. This class provides a constructor for creating new StringReader and various of methods( either inherited from its super class or of itself) to do work in various ways such as to read string, mark the position etc.
Constructor of StringReader
| StringReader(String s) | This constructor is used to create a new StringReader which source is a
string. Syntax : public StringReader(String s) |
Methods in StringReader
Example
An example is being given here which will demonstrate you about how to use the StringReader class in Java. In this example I have created a Java class named JavaStringReaderExample.java where I have created a constant string value which will be further read by the StringReader. Then created a new StringReader to read the string as of its input stream. To read the string I have used the read() method.
Source Code
JavaStringReaderExample.java
import java.io.IOException;
import java.io.StringReader;
public class JavaStringReaderExample
{
public static void main(String args[])
{
StringReader sr = null;
String str = "\n Java IO StringReader \n";
try
{
sr = new StringReader(str);
int r;
while((r= sr.read()) != -1)
{
System.out.print((char)r);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
}
finally
{
if(sr != null)
{
try
{
sr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
Output
When you will execute the above example you will get the output as follows :

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java IO StringReader
Post your Comment