[Java] 统计文本文件的行数,单词书,字节数 →→→→→进入此内容的聊天室

来自 , 2019-08-15, 写在 Java, 查看 94 次.
URL http://www.code666.cn/view/c399862d
  1. import java.io.*;
  2.  
  3. /**
  4.  * 统计文本文件的行数,单词书,字节数
  5.  */
  6. class WordCount {
  7.         public static int words = 1;
  8.         public static int lines = 1;
  9.         public static int chars = 0;
  10.  
  11.         public static void wc(InputStream f) throws IOException {
  12.                 int c = 0;
  13.                 boolean lastNotWhite = false;
  14.                 String whiteSpace = " \t\n\r";
  15.                 while ((c = f.read()) != -1) {
  16.                         chars++;
  17.                         if (c == '\n') {
  18.                                 lines++;
  19.                         }
  20.                         if (whiteSpace.indexOf(c) != -1) {
  21.                                 if (lastNotWhite) {
  22.                                         words++;
  23.                                 }
  24.                                 lastNotWhite = false;
  25.                         } else {
  26.                                 lastNotWhite = true;
  27.                         }
  28.                 }
  29.         }
  30.  
  31.         public static void main(String args[]) {
  32.                 FileInputStream f;
  33.                 try {
  34.                         if (args.length == 0) { // We're working with stdin
  35.                                 f = new FileInputStream("c:/123.txt");
  36.                                 wc(f);
  37.                         } else { // We're working with a list of files
  38.                                 for (int i = 0; i < args.length; i++) {
  39.                                         f = new FileInputStream(args[i]);
  40.                                         wc(f);
  41.                                 }
  42.                         }
  43.                 } catch (IOException e) {
  44.                         return;
  45.                 }
  46.                 System.out.println(lines + "行 " + words + "个单词 " + chars + "个字节");
  47.         }
  48. }
  49.  

回复 "统计文本文件的行数,单词书,字节数"

这儿你可以回复上面这条便签

captcha