Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java IO 流實作大檔案分割與合併的完整範例

為什麼需要把檔案切開?

檔案分割是個看似冷門、實際上非常實用的技巧。想像一個情境:手上有一個 3GB 的檔案要從 A 電腦搬到 B 電腦,但你唯一的儲存媒介是一張 1GB 的 SD 卡。這時候把檔案切成三份 1GB 的碎片,分批複製過去,再還原成一個整體,問題就解決了。

另一個常見場景是上傳限制。有些 FTP 伺服器會硬性規定單一檔案不得超過 10MB,而你手上偏偏有一個幾百 MB 的備份檔。同樣的思維——先切、再傳、最後合併——就能繞過限制。

既然切開了,用回來之前就得有還原的能力。本文用 Java 的 IO 流,把「分割」與「合併」兩件事各寫成一個方法。

實作前的準備

測試標的是本機的 E:\eclipse-jee-juno-win32.zip(就拿這個大家又愛又恨的 IDE 來開刀)。

分割前的檔案狀態:

分割後的檔案狀態:

分割:splitFileDemo

參數只有兩個:要處理的檔案物件,以及希望切成幾份。程式會先取得原始檔的總長度、主檔名與副檔名,然後逐一產生 檔名_data1.副檔名、檔名_data2.副檔名 這樣的碎片。每寫滿「總長度 ÷ 份數」就換下一個輸出檔,因此不需要把整個檔案讀進記憶體。

//檔案分割:傳入要分割的檔案與份數
private static void splitFileDemo(File src, int m) {
    if (src.isFile()) {
        long l = src.length(); //檔案總長度
        String fileName = src.getName().substring(0, src.getName().indexOf("."));
        String endName = src.getName().substring(src.getName().lastIndexOf("."));
        InputStream in = null;
        try {
            in = new FileInputStream(src);
            for (int i = 1; i <= m; i++) {
                StringBuffer sb = new StringBuffer();
                sb.append(src.getParent()).append("\\").append(fileName)
                   .append("_data").append(i).append(endName);
                File file2 = new File(sb.toString());
                OutputStream out = new FileOutputStream(file2);
                int len = -1;
                byte[] bytes = new byte[10 * 1024 * 1024]; //10MB 緩衝區
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                    if (file2.length() > (l / m)) {
                        break; //寫滿一份,換下一個檔案
                    }
                }
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

合併:joinFileDemo

合併的思路比分割更單純:從碎片檔名中還原主檔名與副檔名,然後用 FileOutputStream(file, true) 的「附加」模式,把每份碎片依序倒進同一個輸出檔。這裡的 true 是關鍵,它讓每次開檔都接在既有內容之後,而不是把前面寫的內容清掉。

//檔案合併:傳入要合併的碎片路徑(可變參數)
private static void joinFileDemo(String... src) {
    for (int i = 0; i < src.length; i++) {
        File file = new File(src[i]);
        String fileName = file.getName().substring(0, file.getName().indexOf("_"));
        String endName = file.getName().substring(file.getName().lastIndexOf("."));

        StringBuffer sb = new StringBuffer();
        sb.append(file.getParent()).append("\\").append(fileName).append(endName);
        try {
            InputStream in = new FileInputStream(file); //讀取小檔案
            File file2 = new File(sb.toString());
            OutputStream out = new FileOutputStream(file2, true); //附加寫入大檔案
            int len = -1;
            byte[] bytes = new byte[10 * 1024 * 1024];
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("檔案合併完成!");
}

動手前覺得很複雜,寫完發現不過如此

這兩個方法都只用到最原始的 FileInputStream 與 FileOutputStream,沒有任何第三方套件。真正需要留意的細節只有兩個:緩衝區大小會直接影響效能,以及合併時別忘了開啟附加模式。有興趣的人可以試著把它改成「按指定大小切分」或加上 MD5 校驗,練習價值更高。

Copyright © Linux教程網 All Rights Reserved