StringReader class

 

                  see  Reader class  for descriptions of StringReader's methods.  They are:

 

.mark( readAheadLimit )  Mark the present position in the stream.

.markSupported( ) Tell whether this stream supports the mark(...) operation.

.read( )  Read a single character, returning it in the low end two bytes of an int.

.read( char[ ] )  Read characters into a char array.

.read( char[ ], offset, len)  Read characters into a portion of a char array.

.ready( ) Tell whether this stream is ready to be read.

.reset( )  Reset the stream.

.skip( n )  Skip over n characters in the stream.

.close( ) Close the stream.

 

 

  StringReader doesn’t add any methods to Reader's.  But it lets you use Reader's methods to read a String from memory as if it were an I/O stream.

 

  StringReader supports mark(...) and reset( ).

 

  This snippet reads and prints just the first character of a String:

 

import java.io.*;

 

String s = "ABCDEF";

try {

     StringReader sr = new StringReader( s );

     System.out.println( (char) sr.read( ));          // just one char is read here

}

catch (IOException e) { }

 

 

  The above example does the same thing as the one above, but it explicitly shows the returned int. Again, just the first character is read.

 

import java.io.*;

 

String s = "ABCDEF";

 

try {

     StringReader sr = new StringReader( s );

      int x = 0;

     x = sr.read( );

     System.out.println( (char) x );       // just one char is read here

}

catch (IOException e) { }

 

 

  This snippet reads the entire String in a single operation by determining its length first.  Note that, since StringReader's constructor does not throw an IOException, it can be located outside the try-catch block.

 

import java.io.*;

 

String s = "ABCDEFGHIJK";

 

StringReader sr = new StringReader( s );

char[ ] c = new char[ s.length( ) ];

try {

    sr.read( c );                                        // one statement reads the entire String here

    for ( int x = 0;  x < s.length( );  x++ ) {

        System.out.print( c[x] );

    }

} catch (IOException e) { }

 

 

  This snippet reads the entire String, one character at a time, without knowing its length beforehand.

 

import java.io.*;

 

String s = "XYZ";

 

StringReader sr = new StringReader( s );

int x;

try {

        while ( (x = sr.read( )) != -1 ) {      // checks for normal end of stream here

            System.out.print( (char) x );

        }

} catch (IOException e) { }