分块测试
//分块测试@Testpublic 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一份的文件
将分块的视频重新合并
//将分块进行合并@Testpublic 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<File> filesList = Arrays.asList(files);//排序Collections.sort(filesList, new Comparator<File>() {@Overridepublic 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();}