StringReader并不常用,因为通常情况下使用String更简单一些。但是在一些需要Reader作为参数的情况下,就需要将String读入到StringReader中来使用了。
下面的例子代码中,我们创建了一个StringReader实例,然后将此示例作为参数给StreamTokenizer类,然后数给定字符串中一个有多少个单词。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
/**
*
* @author outofmemory.cn
*/
public class Main {
/**
* StringReader示例代码
*/
public void countWordsInAString() {
StreamTokenizer streamTokenizer = null;
String stringToBeParsed = "The quick brown fox jumped over the lazy dog";
StringReader reader = new StringReader(stringToBeParsed);
int wordCount = 0;
try {
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);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().countWordsInAString();
}
}