dsa

Java StringReader

In this tutorial, we will learn about the Java StringReader, its constructors and its methods with the help of an example.

Java StringReader writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Constructors of StringReader

Methods

MethodsDescription
void close()Closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit)Marks the present position in the stream.
boolean markSupported()Tells whether this stream supports the mark() operation, which it does.
int read()Reads a single character.
int read(char[] cbuf, int off, int len)Reads characters into a portion of an array.
boolean ready()Tells whether this stream is ready to be read.
void reset()Resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.
long skip(long ns)Skips the specified number of characters in the stream.

Examples :


import java.io.StringReader;

public class Codemistic 
{
  	public static void main(String[] args) 
	{

    		String data = "This file consists of a single line.";

    		// Create a character array
    		char[] array = new char[100];

    		try 
		{
      			// Create a StringReader
      			StringReader input = new StringReader(data);

      			//Use the read method
      			input.read(array);
      			System.out.println("Data read from the string:");
      			System.out.println(array);

      			input.close();
    		}
    		catch(Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}

Output :

Data read from the string:
This file consists of a single line.