StreamTokenizer (流标记) 示例

字符,ttype包含该字符的值。如果遇到一个行结束情况,ttype等于TT_EOL(这假定了参数为true调用eolIsSignificant())。如果遇到流的结尾,ttype 等于TT_EOF。

*/

//Enhanced word count program that uses a StreamTokenizer.
import java.io.*;
class STWordCount{
public static int intWords = 0;
public static int intLines = 0;
public static int intChars = 0;
public static void wc(Reader r) throws IOException{
   StreamTokenizer tok = new StreamTokenizer(r);
   tok.resetSyntax();
   tok.wordChars(33,255);
   tok.whitespaceChars(0,' ');
   tok.eolIsSignificant(true);
   while(tok.nextToken() != tok.TT_EOF){
    switch(tok.ttype){
     case tok.TT_EOL: //不知道为什么会报错
      intLines++;
        intChars++;
      break;
     case tok.TT_WORD: //不知道为什么会报错
      intWords++;
     default:
      intChars += tok.sval.length();
    }
   }
}
public static void main(String[] args)
{
   if(args.length == 0){
    try{
     wc(new InputStreamReader(System.in));
     System.out.println(intLines + " " + intWords + " " + intChars);
    }catch(IOException e){
    
    }
   }else{
    int tWords = 0,tLines = 0,tChars = 0;
    for(int i =0;i<args.length;i++){
     try{
      intWords = intLines = intChars = 0;
      wc(new FileReader(args[i]));
      tWords += intWords;
      tLines += intLines;
      tChars += intChars;
      System.out.println(args[i] + ": " +intLines+ " " + intWords + " " + intChars);
     }catch(IOException e){
      System.out.println(args[i] +":error.");
     }
    }
    System.out.println("Total :" +tLines+ " " + tWords + " " + tChars);
   }
}
}

你可能感兴趣的:(StreamTokenizer (流标记) 示例)