It extends Reader. A character stream whose source is a String.
StringReader enables you to turn an ordinary String into a Reader. This is useful if you have data as a String but need to pass that String to a component that only accepts a Reader.
Note: Since the StringReader is not using any underlying system resources like files or network sockets, closing the StringReader is not crucial.
Constructor
Methods
Java Code
packagecom.java.io;importjava.io.IOException;importjava.io.StringReader;publicclassStringReaderExample{publicstaticvoidmain(String[] args){StringReader stringReader =null;String str ="Reading String Data";try{
stringReader =newStringReader(str);// Check if markSupported by StringReaderSystem.out.println("Is Mark Supported:"+ stringReader.markSupported());if(stringReader.markSupported()){// marks the current position// 100 characters to be read before the mark position becomes invalid
stringReader.mark(100);}// Skip 5 characters
stringReader.skip(5);System.out.print("After Skip Content:");// Checks if the stringReader is ready to be readif(stringReader.ready()){for(int i =0; i <14; i++){// Reading one character at a timeSystem.out.print((char) stringReader.read());}}System.out.println("");// Reset to the earlier marked positionSystem.out.println("Reset to the earlier marked position");
stringReader.reset();System.out.print("Reading characters into char Array:");char c[]=newchar[20];if(stringReader.ready()){
stringReader.read(c);for(int i =0; i <20; i++){System.out.print(c[i]);}}}catch(IOException ex){
ex.printStackTrace();}finally{// Closing the streamsif(stringReader !=null)
stringReader.close();}}}
Output
IsMarkSupported:trueAfterSkipContent:ng StringDataResettothe earlier marked position
Reading characters into charArray:ReadingStringData