计算文件中的字符数

时间:2018-03-22 03:01:43

标签: java io

我正在编写代码来计算.txt文件中的字符数,字数和行数。我的示例文本文件有21个单词,2行和114个字符。我的程序输出状态有21个单词,2行和113个字符。该文件大多是贫瘠的,仅用于测试目的。在文件中是:

This is a test for counter function. Contents are subject to change.
This line tests if the line count is correct.

我的节目是:

public static void counter(){
    String file_name = "input.txt";
    File input_file = new File(file_name);
    Scanner in_file = null;

    int word_count = 0;
    int line_count = 0;
    int char_count = 0;
    String line;


    try{
        in_file = new Scanner(input_file);
    }
    catch(FileNotFoundException ex){
        System.out.println("Error: This file doesn't exist");
        System.exit(0);
    }
    try{
        while(in_file.hasNextLine()){
            line = in_file.nextLine();
            char_count = char_count + line.length();
            String[] word_list = line.split(" ");
            word_count = word_count + word_list.length;
            String[] line_list = line.split("[,\\n]");
            line_count = line_count + line_list.length;

        }
    }
    catch(ArrayIndexOutOfBoundsException ex){
        System.out.println("Error: The file format is incorrect");
    }
    catch(InputMismatchException ex){
        System.out.println("Error: The file format is incorrect");
    }
    finally{
        System.out.print("Number of words: ");
        System.out.println(word_count);
        System.out.print("Number of lines: ");
        System.out.println(line_count);
        System.out.print("Number of characters: ");
        System.out.println(char_count);
        in_file.close();
    }
}

1 个答案:

答案 0 :(得分:0)

正确的代码是

public void calculateFileCharecteristics(String fileName){
    try(BufferedReader bufferedReader = new BufferedReader(new FileReader(new 
    File(filename)))){
        String line;
        int lineCount = 0;
        int totalCharCount = 0;
        while((line=bufferedReader.readLine())!=null){
            lineCount++; 
            int charCount = line.split("\n").length;
            totalCharCount +=charCount;
        }
    }
}