分块测试
//分块测试
@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一份的文件 文章来源:https://www.toymoban.com/news/detail-829041.html
将分块的视频重新合并文章来源地址https://www.toymoban.com/news/detail-829041.html
//将分块进行合并
@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<File> filesList = Arrays.asList(files);
//排序
Collections.sort(filesList, new Comparator<File>() {
@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();
}
到了这里,关于对视频进行分块,断点续传的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!