对视频进行分块,断点续传

 分块测试

    //分块测试
    @Test
    public void testChunk() throws IOException {
        //源路径
        File sourceFile = new File("D:\\BaiduNetdiskDownload\\Day1-00.项目导学.mp4");
        //分块文件存储路径
        String chunkFilePath = "D:\\develop\\chunk\\";
        //分块文件大小
        int chunkSize = 1024*1024*1;
        //分块文件个数
        int chunkNum = (int) Math.ceil(sourceFile.length()*1.0/chunkSize);
        //使用流从源文件读数据,向分块文件中读数据
        RandomAccessFile raf_r = new RandomAccessFile(sourceFile,"r");
        byte[] bytes = new byte[1024];
        for (int i = 0; i < chunkNum; i++) {
            //创建分块文件夹
            File chunkFile = new File(chunkFilePath + i);
            //创建分块文件写入流
            RandomAccessFile raf_rw = new RandomAccessFile(chunkFile, "rw");
            int len = -1;
            //将数据读到缓冲区中
            while((len=raf_r.read(bytes))!=-1){
                //将数据从缓冲区读出后写入文件中
                raf_rw.write(bytes,0,len);
                if(chunkFile.length()>=chunkSize){
                    break;
                }
            }
            raf_rw.close();
        }
        raf_r.close();
    }

将视频分块成1mb一份的文件 对视频进行分块,断点续传_第1张图片

将分块的视频重新合并

//将分块进行合并
    @Test
    public void testMerge() throws IOException {
        //块文件目录
        File chunkFolder = new File("D:\\develop\\chunk\\");
        //源文件
        File sourceFile = new File("D:\\BaiduNetdiskDownload\\Day1-00.项目导学.mp4");
        //合并后的文件
        File mergeFile = new File("D:\\develop\\Day1-00.项目导学2.mp4");
        //取出所有分块文件
        File[] files = chunkFolder.listFiles();

        List filesList = Arrays.asList(files);
        //排序
        Collections.sort(filesList, new Comparator() {
            @Override
            public int compare(File o1, File o2) {
                return Integer.parseInt(o1.getName())-Integer.parseInt(o2.getName());
            }
        });

        //写入流
        RandomAccessFile raf_rw = new RandomAccessFile(mergeFile,"rw");
        //缓冲区
        byte[] bytes = new byte[1024];

        for (File file : filesList) {
            int len = -1;
            //读分块的流
            RandomAccessFile raf_r = new RandomAccessFile(file,"r");
            while ((len=raf_r.read(bytes))!=-1){
                raf_rw.write(bytes,0,len);
            }
            raf_r.close();
        }
        raf_rw.close();
    }

你可能感兴趣的:(java)