首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 檔案操作實作:統計檔案中字母、數字、空白、行數

     編輯:Java 相關知識

本文示範使用 BufferedReader 逐行讀取文字檔案,利用 Character 工具類分類統計字符類型:字母、數字、空白字符、總行數。適用於日誌分析、程式碼統計、文字檔案審計等場景。

完整實作程式碼

import java.io.*;

public class FileCharCounter {
    public static void main(String[] args) {
        String fileName = "D:/date.java.bak"; // 修改為實際檔案路徑
        countFileChars(fileName);
    }

    public static void countFileChars(String fileName) {
        int letters = 0, digits = 0, whitespaces = 0, lines = 0;

        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines++;
                char[] chars = line.toCharArray();
                for (char c : chars) {
                    if (Character.isLetter(c)) {
                        letters++;
                    } else if (Character.isDigit(c)) {
                        digits++;
                    } else if (Character.isWhitespace(c)) {
                        whitespaces++;
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("讀取檔案失敗: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        System.out.printf("統計結果 - 字母: %d, 數字: %d, 空白: %d, 行數: %d%n",
                letters, digits, whitespaces, lines);
    }
}

關鍵 API 說明

進階擴充:支援編碼指定與大檔案

public static void countFileCharsAdvanced(String fileName, String encoding) throws IOException {
    // 使用 NIO Files.newBufferedReader 明確指定編碼
    try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName), Charset.forName(encoding))) {
        // 統計邏輯相同...
    }
}

// 大檔案並行統計 (Java 8+ Stream)
public static void countParallel(String fileName) throws IOException {
    long[] counts = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)
        .parallel()
        .mapToInt(line -> {
            int l=0, d=0, w=0;
            for (char c : line.toCharArray()) {
                if (Character.isLetter(c)) l++;
                else if (Character.isDigit(c)) d++;
                else if (Character.isWhitespace(c)) w++;
            }
            return new int[]{l, d, w, 1}; // letters, digits, whitespaces, lines
        })
        .reduce(new int[]{0,0,0,0}, (a,b) -> new int[]{
            a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3]
        });
    System.out.printf("並行統計 - 字母:%d 數字:%d 空白:%d 行數:%d%n",
            counts[0], counts[1], counts[2], counts[3]);
}

常見陷阱與注意事項

  • 編碼不匹配:預設使用平台預設編碼,中文系統常為 GBK,建議明確指定 StandardCharsets.UTF_8 或檔案實際編碼
  • readLine() 不保留換行符:\n/\r\n 不會計入空白統計,若需統計換行請額外處理
  • 補充字符 (Emoji、生僻字) 佔 2 個 char (UTF-16 代理對),Character.isLetter 對代理對單獨判斷會失效,需用 Character.isLetter(codePoint) 配合 codePoints() 流處理
  • 二進位檔案:此邏輯僅適用文字檔,二進位檔會產生大量非可列印字符

效能優化建議

  • 小檔案 (<10MB):單執行緒 BufferedReader 足夠
  • 大檔案 (>100MB):Files.lines().parallel() 或 MappedByteBuffer 記憶體映射
  • 極大檔案 (>GB):分塊讀取 + 線程池聚合,避免 OOM
  • 頻繁統計同檔案:考慮建立索引或快取結果

此範例展示了 Java 檔案 I/O 與字符分類的基礎用法,可直接擴充為程式碼行數統計器 (cloc 簡易版)、日誌關鍵字計數器等實用工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法說明包含範例
Character.isLetter(char)判斷是否為 Unicode 字母a-z, A-Z, 中文漢字, 日文假名, 希臘字母等
Character.isDigit(char)判斷是否為 Unicode 數字0-9, 全形數字 0-9, 羅馬數字 ⅰ-ⅹ 等
Character.isWhitespace(char)判斷是否為空白字符空格, Tab(\t), 換行(\n), 製表符, 不可中斷空格(\u00A0) 等