CodeGym /課程 /JAVA 25 SELF /非同步處理文字檔案

非同步處理文字檔案

JAVA 25 SELF
等級 56, 課堂 2
開放

1. 分段讀取檔案:ByteBuffer 與編碼

如今我們很少處理小型的文字檔。通常面對的是龐大的伺服器日誌、報表、CSV 檔,或是數 GB 的資料傾印。因此,重點不只是在於讀取檔案,而是要有效率地讀,且不讓應用程式「卡住」。

非同步作法正是為此而生: 它不會阻塞主執行緒 — 無論是介面或伺服端邏輯, — 允許平行讀寫大量資料,並在需要同時處理多個檔案時,讓應用程式更具延展性。

要弄清的一點是: 非同步 I/O 並不會讓磁碟本身更快 — 沒有奇蹟。它只是讓你的程式在等待磁碟完成操作時,不必發呆,可以去做其他事情。

非同步讀取如何運作?

非同步通道 (AsynchronousFileChannel) 讀取的不是字串,而是位元組區塊到 ByteBuffer 物件。這就好比你搬的是一箱箱字母,而不是一個個單字。讀完之後,你需要把這些位元組轉成字串 — 而且要考慮編碼!

範例: 以區塊方式非同步讀取檔案

我們寫一個簡單範例: 以 4096 位元組為一個區塊非同步讀檔,並將內容輸出到主控台。

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.nio.charset.StandardCharsets;
import java.io.IOException;

public class AsyncTextReadExample {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("bigfile.txt");
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            long position = 0;
            int bytesRead;
            Future<Integer> future = channel.read(buffer, position);

            while ((bytesRead = future.get()) > 0) {
                buffer.flip();
                // 將位元組解碼為字串 (UTF-8)
                String chunk = StandardCharsets.UTF_8.decode(buffer).toString();
                System.out.print(chunk);
                buffer.clear();
                position += bytesRead;
                future = channel.read(buffer, position);
            }
        }
    }
}

重點:

  • 以分段(緩衝區)方式讀取檔案,而非一次讀完整個檔案。
  • 讀取後,使用 Charset 將位元組解碼為字串。
  • 處理完畢後要清空緩衝區:如果所有位元組都已解碼,呼叫 buffer.clear();如果區塊末尾可能殘留不完整字元的位元組,則呼叫 buffer.compact()。
  • 這個範例遇到多位元組字元就會出錯:Charset.decode() 會把在區塊邊界被「切開」的字元替換成「�」。原因與修正方法請見下文。

為什麼僅僅解碼位元組還不夠?

問題在於,字元可能會跨兩個區塊「被切開」,特別是使用多位元組編碼(例如,"UTF-8")時。如果緩衝區中的最後一個位元組只是某個字元的一半,下一個區塊就會以該字元的「剩餘部分」開始。若沒有特別處理,你會得到亂碼,甚至發生解碼錯誤。

2. 位元組轉字串: 處理斷裂

行被分割的問題

假設你有字串 "你好\n世界\n",而緩衝區剛好結束在 "你",而 "好\n世界\n" 落在下一個區塊。若只是把字串硬拼起來,可能會遺失字元或得到不正確的字串。

解法: 使用 CharsetDecoder

Java 提供了 CharsetDecoder 類別,能正確處理此類情形。不過,它本身並不會記住位元組:如果緩衝區末尾是某個多位元組字元的開頭,decode() 會把這些位元組留在 ByteBuffer 中,緩衝區的位置就停在它們前面。你的任務是別弄丟它們:解碼之後請呼叫 buffer.compact(),而不是 buffer.clear()。compact() 方法會把尚未解碼的位元組搬到緩衝區開頭,下一次讀取會把新的位元組緊接在它們後面寫入。

CharsetDecoder 使用範例

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;

CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
ByteBuffer buffer = ... // 你的位元組
CharBuffer charBuffer = CharBuffer.allocate(buffer.capacity());
decoder.decode(buffer, charBuffer, false);
// 現在 charBuffer 已含有正確解碼的字元

不需要另外保存位元組的「剩餘」部分:呼叫 compact() 之後,ByteBuffer 本身就會保存它。輸入結束時,最後一次以 endOfInput = true 呼叫 decode,接著呼叫 decoder.flush(charBuffer),這是 CharsetDecoder 的契約所要求的。另外也要檢查 decode 的回傳結果:遇到損壞的位元組時,它會回報錯誤,而不會繼續往下處理。

3. 文字檔的非同步寫入

讀取只是工作的一半。寫入同樣以位元組區塊進行,而這些位元組必須先從字串(經由編碼)取得。

範例: 非同步將字串寫入檔案

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.nio.charset.StandardCharsets;

public class AsyncTextWriteExample {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("output.txt");
        String text = "你好,世界!\n";
        ByteBuffer buffer = ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8));
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
            Future<Integer> future = channel.write(buffer, 0);
            // 為了示範先等待完成(一般不必這樣做!)
            future.get();
            System.out.println("資料已以非同步方式寫入。");
        }
    }
}

說明: 在真正的非同步情境下,不要在主執行緒呼叫 future.get() —— 這會把非同步程式碼變回同步。最好使用 CompletionHandler(參見前一講)。

4. 實作: 非同步讀取大型文字檔並計算行數

我們來實作一個任務: 以非同步方式讀取大型文字檔,並計算換行符號("\n")的數量。結果 — 在主控台輸出行數。

使用 CompletionHandler 的範例

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.StandardCharsets;
import java.nio.CharBuffer;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

public class AsyncLineCounter {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("bigfile.txt");
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);

        ByteBuffer buffer = ByteBuffer.allocate(4096);
        AtomicLong position = new AtomicLong(0);
        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
        StringBuilder leftover = new StringBuilder();
        AtomicLong lines = new AtomicLong(0);

        channel.read(buffer, position.get(), null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                boolean endOfInput = (result == -1); // -1: 檔案已讀到結尾
                buffer.flip();
                // +1:預留空間,給解碼器可能「保留」到輸入結束的字元
                CharBuffer charBuffer = CharBuffer.allocate(buffer.remaining() + 1);
                CoderResult cr = decoder.decode(buffer, charBuffer, endOfInput);
                if (!cr.isError() && endOfInput) {
                    cr = decoder.flush(charBuffer); // 在最後一次 decode(..., true) 之後
                }
                if (cr.isError()) {
                    // 損壞的位元組:若沒有這項檢查,「compact → read → decode」迴圈將無法前進
                    try { cr.throwException(); } catch (CharacterCodingException e) { failed(e, attachment); }
                    return;
                }
                charBuffer.flip();
                String chunk = leftover.toString() + charBuffer.toString();
                leftover.setLength(0);

                // 計算行數
                int last = 0;
                int idx;
                while ((idx = chunk.indexOf('\n', last)) != -1) {
                    lines.incrementAndGet();
                    last = idx + 1;
                }
                // 剩餘部分(最後一個 \n 之後的片段)
                if (last < chunk.length()) {
                    leftover.append(chunk.substring(last));
                }

                if (endOfInput) {
                    // 沒有以 '\n' 結尾的最後一行也算作一行
                    if (leftover.length() > 0) lines.incrementAndGet();
                    System.out.println("檔案中的行數: " + lines.get());
                    try { channel.close(); } catch (IOException e) { e.printStackTrace(); }
                    return;
                }
                // 尚未解碼的位元組(被「切開」的字元開頭)仍留在 buffer 中。
                // compact() 會把它們移到緩衝區開頭,下一次讀取會把新位元組接在它們後面。
                buffer.compact();
                position.addAndGet(result);
                channel.read(buffer, position.get(), null, this);
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.err.println("讀取錯誤: " + exc.getMessage());
                try { channel.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        });

        // 為避免程式過早結束(僅作示範!)
        try { Thread.sleep(2000); } catch (InterruptedException e) {}
    }
}
  • 我們使用 CompletionHandler 來撰寫真正的非同步程式碼。
  • 每次讀取後,緩衝區都會透過 CharsetDecoder 解碼。
  • 未以 "\n" 結尾的行之剩餘部分會帶到下一個區塊。
  • 區塊末尾尚未解碼的位元組會留在 buffer 中,compact() 會把它們保留到下一次讀取。而 leftover 則是行的尾巴(已經是字元),只用於計算行數。
  • 當 read 回傳 -1 時,我們最後一次呼叫 decode(..., true) 與 flush()。如果位元組損壞,decode 會回報錯誤,我們就把它交給 failed(),否則讀取迴圈會無限循環下去。
  • 讀到檔案結尾後,若 leftover 仍有內容,也算作一行。
  • 為求簡單,範例會「睡」2000 毫秒以等待非同步操作完成(在實際應用中通常不需要 — 通常會有主迴圈或 UI)。

5. 以非同步方式將結果寫入檔案

假設我們想把結果(例如行數)寫入新檔案 — 同樣以非同步方式。

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.charset.StandardCharsets;
import java.io.IOException;

public class AsyncWriteResult {
    public static void main(String[] args) throws IOException {
        String result = "檔案中的行數: 12345\n";
        ByteBuffer buffer = ByteBuffer.wrap(result.getBytes(StandardCharsets.UTF_8));
        Path path = Path.of("result.txt");

        AsynchronousFileChannel channel = AsynchronousFileChannel.open(
            path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        channel.write(buffer, 0, null, new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer written, Object attachment) {
                System.out.println("結果已以非同步方式寫入!");
                try { channel.close(); } catch (IOException e) { e.printStackTrace(); }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.err.println("寫入錯誤: " + exc.getMessage());
                try { channel.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        });

        try { Thread.sleep(500); } catch (InterruptedException e) {}
    }
}

6. 處理部分資料與編碼的建議

跨區塊的部分行

如果一個字元被拆在兩個區塊之間,請不要手動去「拼接」位元組!CharsetDecoder 會停在不完整的字元之前,而 buffer.compact() 會把它的位元組保留到下一次讀取。

處理不同編碼

"UTF-8" 是現代應用程式的標準,但若檔案使用其他編碼(例如,"Windows-1251" 或 "UTF-16"),請使用對應的 Charset:

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

Charset charset = Charset.forName("Windows-1251");
CharsetDecoder decoder = charset.newDecoder();

使用 CharsetDecoder 與 CharsetEncoder

當你以分段方式讀寫資料時,正確處理編碼非常重要。字元可能會被拆在兩個區塊之間,若沒有額外處理,就會變成一團亂碼。

為了避免這種情況,請使用 CharsetDecoder 與 CharsetEncoder。

讀取時呼叫 decode(ByteBuffer, CharBuffer, endOfInput),寫入時呼叫 encode(CharBuffer, ByteBuffer, endOfInput)。

解碼器會停在不完整的字元之前,並把它的位元組留在輸入緩衝區中。只有保留這些位元組(compact())並交給下一次 decode 呼叫,才能把字元組裝完整。

7. 非同步處理文字檔的常見錯誤

錯誤 №1: 在區塊之間遺失尚未解碼的位元組。 如果在 decode 之後呼叫 buffer.clear(),被「切開」的多位元組字元開頭就會消失:下一個區塊會從字元的中間開始,解碼器會回報錯誤或產生亂碼。請改為呼叫 buffer.compact()。

錯誤 №2: 不正確的緩衝區操作. 處理完後忘了呼叫 buffer.clear() 或 buffer.compact() —— 下一次 read 可能無法運作或資料會不正確。

錯誤 №3: 使用了不相符的編碼. 若以與檔案實際編碼不一致的 Charset 來解碼位元組,可能會出現亂碼,甚至錯誤。

錯誤 №4: 阻塞主執行緒. 如果你在 UI 執行緒呼叫 future.get() 或 Thread.sleep(),就失去了非同步的意義。請使用 CompletionHandler 與反應式作法。

錯誤 №5: 操作完成後未關閉通道. 無論是否發生錯誤,所有操作完成後務必關閉通道(channel.close())。

1
任務
JAVA 25 SELF, 等級 56, 課堂 2
上鎖
快步秘書:在龐大報告中非同步計算行數 📊
快步秘書:在龐大報告中非同步計算行數 📊
1
任務
JAVA 25 SELF, 等級 56, 課堂 2
上鎖
自動化資料工廠:讀取、處理與非同步匯出 🤖
自動化資料工廠:讀取、處理與非同步匯出 🤖
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION