黑马程序员-JAVA高级视频_IO输入与输出-20天-9(切割合并文件)

时间:2021-11-22 10:58:59
package string.test;

import java.io.*;
import java.util.Vector;

/*
 * 切割文件
 */
public class SplitFile {
    public static void main(String[] args) throws IOException {
        // splitFile();
        merge();
    }

    /*
     * 合并文件
     */
    public static void merge() throws IOException {
        Vector<FileInputStream> fileInputStreams = new Vector<FileInputStream>();
        for (int i = 1; i <= 7; i++) {
            fileInputStreams.add(new FileInputStream("g:\\split" + i + ".rar"));
        }
        SequenceInputStream sis = new SequenceInputStream(fileInputStreams.elements());
        FileOutputStream fos = new FileOutputStream("f:\\alipaydirect.rar");
        byte[] bytes = new byte[1024 * 1024];
        int len = 0;
        while ((len = sis.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }
        sis.close();
        fos.close();

    }

    /*
     * 切割文件
     */
    public static void splitFile() throws IOException {
        FileInputStream fis = new FileInputStream("g:\\alipaydirect.rar");
        FileOutputStream fos = null;
        byte[] bytes = new byte[1024 * 1024];
        int len = 0;
        int count = 1;
        while ((len = fis.read(bytes)) != -1) {
            fos = new FileOutputStream("g:\\split" + count + ".rar");
            count++;
            fos.write(bytes, 0, len);
            fos.flush();
            fos.close();
        }
        fis.close();
    }
}