Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java StringReader Class

In this tutorial, we will learn about the StringReader class in Java. In this class, we can specify a string as a source from where characters are read individually. This class belongs to the java.io package.

Syntax

This is the syntax declaration of the StringReader class. We can see this class is extending the Reader class.

public class StringReader extends Reader  

Methods of StringReader Class

All the methods of the StringReader method are given in the table below:

Method Description
int read() This method is used to read a single character.
int read(char[] cbuf, int off, int len) This method is used to read a character into a portion of an array.
boolean ready() This method is used to tell whether the stream is ready to be read.
boolean markSupported() This method is used to tell whether the stream support mark() operation.
long skip(long ns) This method is used to skip the specified number of character in a stream
void mark(int readAheadLimit) This method is used to mark the present position in a stream.
void reset() This method is used to reset the stream.
void close() This method is used to close the stream.

Java StringReader Example

In the following example, we are using read() method, this method reads each character of the string one by one. we can also implement this method in another way .i.e. read(char[] array, int start, int length) here array is the source and start is the starting position from where we want to start reading, the length is the length of the string.

package studytonight;
import java.io.StringReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try{
			String str = "Hello"; 
			StringReader reader= new StringReader(str); 
			int ch; 
			for (int i = 0; i < 5; i++) { 
				ch = reader.read(); 
				System.out.print((char)ch);
			} 
			reader.close(); 
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


Hello

Conclusion

In this tutorial, we learned about the StringReader class. This class specifies a string as a source from where characters are read individually. This class belongs to the java.io class.