Class FixedWidthReader

java.lang.Object
io.leandev.appfuse.csv.FixedWidthReader
All Implemented Interfaces:
AutoCloseable

public class FixedWidthReader extends Object implements AutoCloseable

固定寬度文本讀取器

讀取固定寬度格式的文本檔案,每個欄位有預定義的字元寬度。

設計原則 此類別提供與 CsvReader 一致的 API,但處理固定寬度格式。 由於 Jackson CSV 不支援固定寬度,採用手動解析方式實作。

使用範例

try (InputStream is = new FileInputStream("report.txt");
     FixedWidthReader reader = new FixedWidthReader(is, settings)) {

    reader.readHeaders();

    for (CsvRecord record = reader.read(); record != null; record = reader.read()) {
        String code = record.getAsString("code").trim();
        String name = record.getAsString("name").trim();
        // 處理資料...
    }
}
Since:
1.0
  • Constructor Details

    • FixedWidthReader

      public FixedWidthReader(InputStream inputStream, FixedWidthReaderSettings settings, Charset charset)
      建構固定寬度讀取器
      Parameters:
      inputStream - 輸入串流
      settings - 讀取設定
      charset - 字元編碼
    • FixedWidthReader

      public FixedWidthReader(InputStream inputStream, FixedWidthReaderSettings settings)
      建構固定寬度讀取器(使用 UTF-8 編碼)
      Parameters:
      inputStream - 輸入串流
      settings - 讀取設定
  • Method Details

    • readHeaders

      public List<String> readHeaders() throws IOException
      讀取 Header 欄位 此方法會讀取第一行資料並設定為 Header。 呼叫後,後續的 read() 將從第二行開始讀取。
      Returns:
      Header 欄位列表
      Throws:
      IOException - 讀取失敗
    • read

      public CsvRecord read() throws IOException
      讀取下一筆資料
      Returns:
      資料記錄,若已讀取完畢則回傳 null
      Throws:
      IOException - 讀取失敗
    • readAll

      public List<CsvRecord> readAll()
      讀取所有資料 注意:此方法會將所有資料載入記憶體,不適合大型檔案。 對於大型檔案請使用 stream()read()
      Returns:
      所有資料記錄
    • stream

      public Stream<CsvRecord> stream()
      取得串流,用於函數式處理 串流模式下,記憶體佔用穩定,適合處理大型檔案
      Returns:
      資料記錄串流
    • skip

      public long skip(long offset) throws IOException
      跳過指定行數
      Parameters:
      offset - 要跳過的行數
      Returns:
      實際跳過的行數
      Throws:
      IOException - 讀取失敗
    • close

      public void close() throws IOException
      Specified by:
      close in interface AutoCloseable
      Throws:
      IOException