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

Java SequenceInputStream 合併多個輸入流:文件拼接實戰示例

     編輯:關於C++

SequenceInputStream 簡介

SequenceInputStream 將多個 InputStream 邏輯串聯為一個流,讀取時依次從各子流讀取,直到所有流耗盡。構造函數支持兩參數版或 Enumeration 版(多流)。

文件拼接實戰


import java.io.*;

public class MergeFiles {
    public static void main(String[] args) throws IOException {
        File dir = new File("d:/data");
        File[] files = {new File(dir, "a.txt"), new File(dir, "b.txt")};
        File outFile = new File(dir, "merged.txt");

        // 構造多流枚舉
        Vector vec = new Vector<>();
        for (File f : files) vec.add(new FileInputStream(f));
        SequenceInputStream sis = new SequenceInputStream(vec.elements());

        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            byte[] buf = new byte[8192];
            int len;
            while ((len = sis.read(buf)) != -1)
                fos.write(buf, 0, len);
        } // try-with-resources 自動關閉 fos
        sis.close(); // 關閉 sis 會級聯關閉所有子流
    }
}

關鍵注意點

  • 關閉順序:關閉 SequenceInputStream 會自動關閉所有子流,無需單獨關閉。
  • 異常處理:任一子流拋出異常會中斷整個讀取流程。
  • 標記/重置:SequenceInputStream 不支持 mark/reset。
  • 內存效率:使用緩衝區批量讀寫,避免單字節操作開銷。

擴展:動態添加流

若運行時動態確定流列表,用 Enumeration 包裝 Vector 或自定義 Enumeration 實現。

替代方案對比

方案優點缺點
SequenceInputStream標準庫、零拷貝邏輯、自動關閉不支持 mark、異常傳播
手動循環讀寫完全控制、易錯誤處理樣板代碼多
Files.copy + Files.write (NIO2)高性能、原子寫入需臨時文件或內存緩衝
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved