Java大文件高效分片、合并实战
工作中有时候会遇到文件需要分片的应用场景,比如文件太大需要切割成多份文件上传等。
下面就跟着我一起开始吧
package com.chow.spirngbootdemo;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
/**
* @author Herman Email: dg_chow@163.com
* @date 2017-7-31 14:35
*/
public class MultipartUploadSender {
public static final int BUF_SIZE = 1024 * 1204;
public static final long MULTIPART_SIZE = 200 * 1024 * 1024;
public static void main(String[] args) {
String sourceFile = "D:\\MyProjects\\docker.zip";
String targetPath = "D:\\MyProjects\\";
String newFilePath = "D:\\MyProjects\\aaa.zip";
// 分片开始-方式1
long current = System.currentTimeMillis();
MultipartUploadSender.fileSpilt(sourceFile, targetPath, MULTIPART_SIZE);
System.out.println("普通IO方式用时(毫秒):" + (System.currentTimeMillis() - current));
// 分片开始-方式2
long current2 = System.currentTimeMillis();
List<String> fileNames = MultipartUploadSender.fileSpiltWithNio(sourceFile, targetPath, MULTIPART_SIZE);
System.out.println("NIO方式用时(毫秒):" + (System.currentTimeMillis() - current2));
// 开始合并
File[] fileList = FileFilter(targetPath, fileNames);
mergeFileWithNio(fileList, newFilePath);
}
/**
* 普通IO分片方式
*
* @param sourceFile 要分片的文件
* @param targetPath 输出路径
* @param multipartSize 文件被切割的大小,单位:byte
* <p>
* model各个参数详解
* r 代表以只读方式打开指定文件
* rw 以读写方式打开指定文件
* rws 读写方式打开,并对内容或元数据都同步写入底层存储设备
* rwd 读写方式打开,对文件内容的更新同步更新至底层存储设备
*/
public static List<String> fileSpilt(String sourceFile, String targetPath, long multipartSize) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
List<String> fileNames = new LinkedList<>();
try {
RandomAccessFile raf = new RandomAccessFile