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

Java 讀取 CSV 檔案完整工具類:支援逗號分隔、逐行逐欄存取

     編輯:Java 相關知識

輕量級 CSV 解析器實作 (無第三方依賴)

使用標準 BufferedReader 逐行讀取,以逗號分割欄位,封裝為可複用的 CsvUtil 類別,支援行/欄/儲存格隨機存取。

核心類別 CsvUtil

package com.huateng.readcsv;

import java.io.*;
import java.util.*;

public class CsvUtil {
    private String fileName;
    private BufferedReader br;
    private List<String> lines = new ArrayList<>();

    public CsvUtil() {}

    public CsvUtil(String fileName) throws Exception {
        this.fileName = fileName;
        br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }
    }

    public List<String> getLines() { return lines; }
    public int getRowCount() { return lines.size(); }

    public int getColCount() {
        if (lines.isEmpty()) return 0;
        String first = lines.get(0);
        if (first.contains(",")) return first.split(",").length;
        return first.trim().isEmpty() ? 0 : 1;
    }

    public String getRow(int rowIndex) {
        return (rowIndex >= 0 && rowIndex < lines.size()) ? lines.get(rowIndex) : null;
    }

    public String getCol(int colIndex) {
        if (getColCount() == 0) return null;
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            String[] cells = line.split(",");
            if (colIndex < cells.length) sb.append(cells[colIndex]).append(",");
        }
        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
    }

    public String getCell(int row, int col) {
        if (row < 0 || row >= lines.size()) return null;
        String[] cells = lines.get(row).split(",");
        return (col >= 0 && col < cells.length) ? cells[col] : null;
    }

    public void close() throws IOException {
        if (br != null) br.close();
    }

    public static void main(String[] args) throws Exception {
        CsvUtil util = new CsvUtil("D:\\demo.csv");
        System.out.println("行數: " + util.getRowCount());
        System.out.println("欄數: " + util.getColCount());
        System.out.println("第 2 行: " + util.getRow(2));
        System.out.println("第 2 欄: " + util.getCol(2));
        
        for (int i = 1; i < util.getRowCount(); i++) {
            for (int j = 0; j < util.getColCount(); j++) {
                System.out.printf("cell[%d][%d]=%s%n", i, j, util.getCell(i, j));
            }
        }
        util.close();
    }
}

功能特性

  • 零依賴:僅使用 JDK 標準庫。
  • 記憶體載入:全檔讀入 List<String>,適合中小檔案 (<100MB)。
  • 多維存取:getRow()、getCol()、getCell(row, col)。
  • 自動偵測欄數:依首行逗號數判斷。

已知限制與改進方向

生產環境推薦:OpenCSV

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.8</version>
</dependency>

try (CSVReader reader = new CSVReader(new FileReader("data.csv"))) {
    String[] headers = reader.readNext();
    List<String[]> rows = reader.readAll();
    // 或逐行處理
    String[] row;
    while ((row = reader.readNext()) != null) { /* ... */ }
}

適用場景總結

  • ✅ 簡單逗號分隔、無特殊字元、中小檔案、快速原型
  • ❌ 複雜 CSV (引號、換行)、大檔案、需型別映射、生產核心業務
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
限制影響改進建議
不支援欄位內含逗號/換行/引號CSV 標準 (RFC 4180) 允許雙引號包裹引入 OpenCSV 或 Apache Commons CSV
全檔載入記憶體大檔案 OOM 風險改為流式處理:逐行回呼/迭代器
編碼固定為平台預設中文 GBK/UTF-8 可能亂碼建構子加入 Charset 參數
無資料型別轉換全為 String外層轉換或整合 Bean 映射庫