大的文件我们需要分片上传
public class BigFileTest {
@Test
public void testChunk() throws IOException {
File sourceFile = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\1.mp4");
File chunkFolderPath = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\chunk\\");
if(!chunkFolderPath.exists()){
chunkFolderPath.mkdirs();
}
int chunkSize = 1024 * 1024 * 1;
long chunkNum = (long) Math.ceil(sourceFile.length() * 1.0 / chunkSize);
RandomAccessFile raf_read = new RandomAccessFile(sourceFile, "r");
byte[] b = new byte[1024];
for (long i = 0; i < chunkNum; i++) {
File file = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\chunk\\" + i);
if(file.exists()){
file.delete();
}
boolean newFile = file.createNewFile();
if(newFile){
RandomAccessFile raf_write = new RandomAccessFile(file, "rw");
int len=-1;
while ((len=raf_read.read(b))!=-1){
raf_write.write(b,0,len);
if(file.length()>=chunkSize){
break;
}
}
raf_write.close();
}
}
raf_read.close();
}
@Test
public void testMerge() throws IOException {
File sourceFile = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\1.mp4");
File chunkFolderPath = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\chunk\\");
if(!chunkFolderPath.exists()){
chunkFolderPath.mkdirs();
}
File mergeFile = new File("C:\\Users\\86173\\Videos\\Radeon ReLive\\1_1.mp4");
boolean newFile1 = mergeFile.createNewFile();
File[] chunkFiles = chunkFolderPath.listFiles();
List<File> chunkFileList = Arrays.asList(chunkFiles);
Collections.sort(chunkFileList, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Integer.parseInt(o1.getName()) - Integer.parseInt(o2.getName()) ;
}
});
RandomAccessFile raf_write = new RandomAccessFile(mergeFile, "rw");
byte[] b = new byte[1024];
for (File file : chunkFileList) {
RandomAccessFile raf_read = new RandomAccessFile(file, "r");
int len=-1;
while ((len=raf_read.read(b))!=-1){
raf_write.write(b,0,len);
}
}
FileInputStream sourceFileStream = new FileInputStream(sourceFile);
FileInputStream mergeFileStream = new FileInputStream(mergeFile);
String sourceMd5Hex = DigestUtils.md5Hex(sourceFileStream);
String mergeMd5Hex = DigestUtils.md5Hex(mergeFileStream);
if(sourceMd5Hex.equals(mergeMd5Hex)){
System.out.println("合并成功");
}
}
}