流式输入/输出 示例

/*

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[i]);
     wc(fr);
    }
   }
  }catch(IOException e){
   return;
  }
  System.out.println(intLines + " " + intWords + " " + intChars);
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值