统计一个文件中的字符数,单词数,制表符。

来源:互联网 发布:js密码和确认密码校验 编辑:程序博客网 时间:2024/05/17 06:33
import java.io.*;import java.util.*;public class TongJi {  public static void main(String args[]) throws Exception {    int charCount = 0, wordCount = 0, lineCount = 0;    // Check usage    if (args.length != 1) {      System.out.println("Usage: java TongJi file");      System.exit(0);    }    // Check if source file exists    File sourceFile = new File(args[0]);    if (!sourceFile.exists()) {       System.out.println("Source file " + args[0] + " not exist");       System.exit(0);    }    // Create a Scanner for the file    Scanner input = new Scanner(sourceFile);    while (input.hasNext()) {      String s = input.nextLine();      charCount += s.length();      lineCount++;      wordCount += countWords(s);    }    System.out.println("File " + sourceFile + " has ");    System.out.println(charCount + " characters");    System.out.println(wordCount + " words");    System.out.println(lineCount + " lines");  }  private static int countWords(String s) {    Scanner input = new Scanner(s);    int count = 0;    while (input.hasNext()) {      input.next(); count++;    }    return count;  }}

这里写图片描述
这里写图片描述

1 0