六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 63|回复: 0

流式输入/输出 示例

[复制链接]

升级  57%

113

主题

113

主题

113

主题

举人

Rank: 3Rank: 3

积分
371
 楼主| 发表于 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[i]);
     wc(fr);
    }
   }
  }catch(IOException e){
   return;
  }
  System.out.println(intLines + " " + intWords + " " + intChars);
 }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表