Using the StringReader class : StringReader « File Input Output « Java






Using the StringReader class

  

import java.io.StreamTokenizer;
import java.io.StringReader;

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);
  }
}
//Number of words in file: 4

   
    
  








Related examples in the same category

1.Read InputStream to string
2.Read string from InputStream and Reader
3.Reads data off a stream, printing every byte read to System.err
4.Reads file contents
5.Reads from an underlying InputStream up to a defined number of bytes or the end of the underlying stream