Java I/O How to - Read from a string via StringReader








Question

We would like to know how to read from a string via StringReader.

Answer

import java.io.StreamTokenizer;
import java.io.StringReader;
//from   w w w  .j a v a  2  s  . c  o m
public class Main {
  public static void main(String[] args) throws Exception{
    StringReader reader = new StringReader("this is a test");

    int wordCount = 0;
    StreamTokenizer streamTokenizer = new StreamTokenizer(reader);

    while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
      if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
        wordCount++;
    }
    System.out.println("Number of words in file: " + wordCount);
  }
}

The code above generates the following result.