StringReader Java


StringReader of character streams is equivalent to StringBufferInputStream of byte streams. We know earlier, the StringBufferInputStream methods are deprecated in favor of StringReader.

Like StringBufferInputStream, the source of data for StringReader is a string. StringReader supports mark() and reset() methods, but StringBufferInputStream does not support. Being character stream, the StringReader operates on Unicode data.

Following is the class Signature

public class StringReader extends Reader

StringReader Java reading from strings

In the program, the string hold by StringReader is read by BufferedReader. StringReader is linked to BufferedReader.

import java.io.*;
public class SRDemo
{
  public static void main(String args[]) throws IOException
  {
    String s1 = "For outsiders\nthe Software engineer\nlooks housed\nin a golden cage";
    StringReader sreader = new StringReader(s1);
    BufferedReader breader = new BufferedReader(sreader);
        
    String s2;
    while( ( s2 = breader.readLine() ) != null)
    {
      System.out.println(s2);
    }
    breader.close();  sreader.close();
  }
}

StringReader Java
Output screen on StringReader Java

The string s1 is delimited with \n and passed as parameter to StringReader. To read each line (separated by \n), the StringReader object sreader is passed to BufferedReader constructor. Using readLine() method of BufferedReader, each string is read and printed.

Pass your comments and suggestions to improve the quality of this tutorial "StringReader Java".

Leave a Comment

Your email address will not be published.