imain 发表于 2013-1-27 04:47:57

流式输入/输出 示例

/*
wc( )方法对任何输入流进行操作并且计算字符数,行数和字数。它在lastNotWhite里追踪字数的奇偶和空格。当在没有参数的情况下执行时,WordCount以System.in为源流生成一个InputStreamReader对象。该流然后被传递到实际计数的 wc( )方法。当在有一个或多个参数的情况下执行时,WordCount 假设这些文件名存在并给每一个文件创建FileReader,传递保存结果的FileReader对象给wc( ) 方法。两种情况下,在退出之前都打印结果。
*/
//A word counting utility.
import java.io.*;
class WordCount{
 public static int intWords = 0;
 public static int intLines = 0;
 public static int intChars = 0;
 public static void wc(InputStreamReader isr) throws IOException{
  int c = 0;
  boolean lastWhite = true;
  String whiteSpace = "\t\n\r";
  while((c=isr.read())!=-1){
   //Count characters.
   intChars++;
   //Count lines.
   if(c=='\n'){
    intLines++;
   }
   //Count words by detecting the start of a word
   int intIndex = whiteSpace.indexOf(c);
   if(intIndex == -1){
    if(lastWhite == true){
     ++intWords;
    }
    lastWhite = false;
   }else{
    lastWhite = true;
   }
  }
  if(intChars !=0){
   ++intLines;
  }
 }
 public static void main(String[] args)
 {
  FileReader fr ;
  try{
   if(args.length ==0){
    //We're working with stdin
    wc(new InputStreamReader(System.in));
   }else{
    //We're working with a list of files.
    for(int i=0;i<args.length;i++){
     fr = new FileReader(args);
     wc(fr);
    }
   }
  }catch(IOException e){
   return;
  }
  System.out.println(intLines + " " + intWords + " " + intChars);
 }
}
页: [1]
查看完整版本: 流式输入/输出 示例