使用BufferedReader(字符流)、BufferedInputStream(字节流)读取文件中的汉字、空格、字母、行数、数字的个数

 File stream = new File("d:/test.txt");
     int num = 0;      //数字数    
          int letter = 0;    //字母数    
          int line = 0;    //行数    
          int space = 0;  //空格数    
          int word= 0;  //汉字数  
    BufferedReader reader=new BufferedReader(new FileReader(stream));//字符流方式获取
    BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream(stream));//字节流方式获取
    String str=null;
    //while((str=reader.readLine())!=null){
    int counts;
    byte []byt=new byte[10240];
    while((counts=inputStream.read(byt, 0, byt.length))!=-1){
    str=new String(byt, 0, counts);
    System.out.println(str);
    //line++;//行数统计
    line+=countLine(str);  //数字统计
    num+=countNumer(str);  //数字统计
    letter+=countLetter(str);//字母
    space+=countSpace(str);//空格
    word+=countWord(str);//汉字
    }
    //字符流方式获取
    while((str=reader.readLine())!=null){
    System.out.println(str);
    line++;//行数统计
    //line+=countLine(str);  //数字统计
    num+=countNumer(str);  //数字统计
    letter+=countLetter(str);//字母
    space+=countSpace(str);//空格
    word+=countWord(str);//汉字
    }
    System.out.println(line);
    System.out.println(num);
    System.out.println(letter);
    System.out.println(space);
    System.out.println(word);
    reader.close();
    inputStream.close();


    }
    //统计行数
    private static int countLine(String str) {
    int line = 0;    //字母数    
  Pattern pattern = Pattern.compile("\\n");
  Matcher matcher = pattern.matcher(str);
  while(matcher.find()){
  line++;
  }
  return line;
}
//统计汉字
   private static int countWord(String str) {
  int word = 0;    //字母数    
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
word++;
}
return word;
}
   //统计空格
   private static int countSpace(String str) {
  int space = 0;    //字母数    
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
space++;
}
return space;
}
//统计文件中出现的字母
private static int countLetter(String str) {
int letter = 0;    //字母数    
Pattern pattern = Pattern.compile("[a-zA-Z]");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
letter++;
}
return letter;
}
//统计字符串中一行中出现中的数字
    private static int countNumer(String str) {
    int count = 0;  
    Pattern pattern=Pattern.compile("\\d");
    Matcher matcher = pattern.matcher(str);
    while(matcher.find()){
    count++;
    }
return count;
}
    
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值