文件分割

package com.company;

import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016-9-13.
 */
public class FIletest {


    public void split(String filePath, int filesize, String path) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("源文件不存在");
        }
        //分割后有多少文件
        long num = file.length() % filesize == 0 ? file.length() / filesize : (file.length() / filesize) + 1;
        System.out.println("一共分为" + num + "份文件");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[filesize];
        int length;
        FileOutputStream fileOutputStream = null;
        for (int i = 0; i < num; i++) {
            if ((length = fileInputStream.read(buffer)) != -1) {
                fileOutputStream = new FileOutputStream(new File(path, i + ".sfz"));
                fileOutputStream.write(buffer, 0, length);
                fileOutputStream.flush();
                fileOutputStream.close();
                System.out.println("copy一份,name为" + i + ".sfz");
            }
        }
        fileInputStream.close();
    }


    public void merge(String name, String filepath) throws IOException {
        File file = new File(filepath);
        if (!file.exists()) {
            throw new IOException();
        }
        File[] files = file.listFiles();
        int length = files.length;
        File filefg = null;
        FileOutputStream fileOutputStream = new FileOutputStream(name);
        FileInputStream fileInputStream = null;
        for (int i = 0; i < length; i++) {
            filefg = new File(filepath, i + ".sfz");
            fileInputStream = new FileInputStream(filefg);
            byte[] buff = new byte[(int) filefg.length()];
            int len = fileInputStream.read(buff);
            if (len != -1) {
                fileOutputStream.write(buff, 0, len);
            }
            fileInputStream.close();
            System.out.println("添加一个文件");
        }
        fileOutputStream.flush();
        fileOutputStream.close();
    }
    


    @Test
    public  void  test1() throws Exception {
        FIletest f = new FIletest();
        f.split("D://诛仙青云志.mp4", 1024 * 1024, "d://诛仙青云志");
    }

    @Test
    public  void  test2() throws Exception {
        FIletest f = new FIletest();
        f.merge("D://诛仙青云志25.mp4", "D://诛仙青云志");
    }
}

 

posted @ 2016-09-13 13:16  宋发准  阅读(176)  评论(0编辑  收藏  举报