文件分割

实现一个文件的分割

    对一个文件进行分割,把要分割的文件和分割成多大的传到方法divison里,先判断文件是不是为空,如果为空直接就结束方法return,如果不为空就 计算一下 把文件分割成几个小文件,用文件大小对cutSize小文件的大小取余,如果能够被整除,小文件的个数就是file.length()/cutSize(文件大小除以小文件的大小),如果不能被整除就,小文件的个数就是file.length()/cutSize+1(这个1用来接收多余的一部分,不够一个cutSize).
    然后new一个BufferderInputStream缓冲流用来读取文件,在定义一个BufferedOutputStream用来写文件,因为小文件的名字每次都不同,所以先不实例化。new 一个byte数组表示每次写书文件的字节。
public class FileDivison {  //文件分割
    private static void divison(File file,long cutSize) {
        if(file == null)return ;  //判断文件是否为空,为空就直接返回return,结束方法
        int num = file.length()%cutSize==0 ? (int)(file.length()/cutSize):(int)(file.length()/cutSize+1);//判断把文件 分割成 几个小文件
        try {
            BufferedInputStream  in = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream out = null;


            byte[] bytes = null;
            int len = -1;
            int count = 0; //记录每个小文件 需要几个byte[1024]的数组
            for(int i =0;i<num;i++) {  //对每一小文件 进行写入
                out = new BufferedOutputStream(new FileOutputStream("D:\\tools\\test1\\"+(i+1)+"_temp"+".wmv"));  //实例化BufferedOutputStream,给小文件一个路径名字
                if(cutSize<1024) {  //如果小文件的大小小于 1024个字节 就用它自己的大小的byte数组来写,这样不会浪费
                    bytes = new byte[(int)cutSize];
                    count = 1;
                }else { //否则 就用1024的byte数组来读取写入
                    bytes = new byte[1024];
                    count = (int)cutSize/1024;//小文件需要读取几次,剩余的部分在下面读取
                }

                while(count>0&&(len = in.read(bytes))!=-1) { 
                    out.write(bytes);
                    out.flush();
                    count--;
                }

                if(cutSize%1024!=0) {  //用来写入小文件的剩余的大小
                    bytes = new byte[(int)cutSize%1024];
                    len = in.read(bytes);
                    out.flush();

                }
                out.close();

            }

            in.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        File file = new File("D:\\tools\\qianfeng\\Day11\\Java_Day11\\视频\\Video_2018-08-08_103749.wmv");//这里是把一个视频进行分割,分割的每段视频大小为20M
        divison(file, 1024*1024*20);
    }
}

猜你喜欢

转载自blog.csdn.net/Lu_Xiao_Yue/article/details/81609933