使用標準 BufferedReader 逐行讀取,以逗號分割欄位,封裝為可複用的 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();
}
}
List<String>,適合中小檔案 (<100MB)。getRow()、getCol()、getCell(row, col)。| 限制 | 影響 | 改進建議 |
|---|---|---|
| 不支援欄位內含逗號/換行/引號 | CSV 標準 (RFC 4180) 允許雙引號包裹 | 引入 OpenCSV 或 Apache Commons CSV |
| 全檔載入記憶體 | 大檔案 OOM 風險 | 改為流式處理:逐行回呼/迭代器 |
| 編碼固定為平台預設 | 中文 GBK/UTF-8 可能亂碼 | 建構子加入 Charset 參數 |
| 無資料型別轉換 | 全為 String | 外層轉換或整合 Bean 映射庫 |