【MinIO】MinIO分块上传和分块合并demo
1. 分块上传demo
@Test
public void testChunk() throws IOException {
File sourceFile = new File("d:/develop/bigfile_test/nacos.avi");
String chunkPath = "d:/develop/bigfile_test/chunk/";
File chunkFolder = new File(chunkPath);
if (!chunkFolder.exists()) {
chunkFolder.mkdirs();
}
long chunkSize = 1024 * 1024 * 1;
long chunkNum = (long) Math.ceil(sourceFile.length() * 1.0 / chunkSize);
System.out.println("分块总数:" + chunkNum);
byte[] b = new byte[1024];
RandomAccessFile raf_read = new RandomAccessFile(sourceFile, "r");
for (int i = 0; i < chunkNum; i++) {
File file = new File(chunkPath + 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();
System.out.println("完成分块" + i);
}
}
raf_read.close();
}
2. 分块合并demo
@Test
public void testMerge() throws IOException {
File sourceFile = new File("D:\\develop\\bigfile_test\\nacos.mp4");
File chunkFolderPath = new File("D:\\develop\\bigfile_test\\chunk\\");
if (!chunkFolderPath.exists()) {
chunkFolderPath.mkdirs();
}
File mergeFile = new File("D:\\develop\\bigfile_test\\nacos_01.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("合并成功");
}
}