使用零拷贝对文件高效的切片和合并

使用零拷贝对文件高效的切片和合并

对文件的切片/合并在应用中是一个很常见的需求,使用 FileChanneltransferTo / transferFrom 的零拷贝方法(需要操作系统支持),可以高效的完成。

切片

/**
 * 对文件按照指定大小进行分片,在文件所在目录生成分片后的文件块儿
 * @param file
 * @param chunkSize
 * @throws IOException
 */
public static void chunkFile(Path file, long chunkSize) throws IOException {
	if (Files.notExists(file) || Files.isDirectory(file)) {
		throw new IllegalArgumentException("文件不存在:" + file);
	}
	if (chunkSize < 1) {
		throw new IllegalArgumentException("分片大小不能小于1个字节:" + chunkSize);
	}
	// 原始文件大小
	final long fileSize = Files.size(file);
	// 分片数量
	final long numberOfChunk = fileSize % chunkSize == 0 ? fileSize / chunkSize : (fileSize / chunkSize) + 1;
	// 原始文件名称
	final String fileName = file.getFileName().toString();
	// 读取原始文件
	try(FileChannel fileChannel = FileChannel.open(file, EnumSet.of(StandardOpenOption.READ))){
		for (int i = 0; i < numberOfChunk; i++) {
			long start = i * chunkSize;
			long end = start + chunkSize;
			if (end > fileSize) {
				end = fileSize;
			}
			// 分片文件名称
			Path chunkFile = Paths.get(fileName + "-" + (i + 1));
			try (FileChannel chunkFileChannel = FileChannel.open(file.resolveSibling(chunkFile), 
									EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))){
				// 返回写入的数据长度
				fileChannel.transferTo(start, end - start, chunkFileChannel);
			}
		}
	}
}

组合

/**
 * 把多个文件合并为一个文件
 * @param file			目标文件	
 * @param chunkFiles	分片文件
 * @throws IOException 
 */
public static void mergeFile (Path file, Path ... chunkFiles) throws IOException {
	if (chunkFiles == null || chunkFiles.length == 0) {
		throw new IllegalArgumentException("分片文件不能为空");
	}
	try (FileChannel fileChannel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))){
		for (Path chunkFile : chunkFiles) {
			try(FileChannel chunkChannel = FileChannel.open(chunkFile, EnumSet.of(StandardOpenOption.READ))){
				chunkChannel.transferTo(0, chunkChannel.size(), fileChannel);
			}
		}
	}
}

最后

零拷贝

3 个赞

注意,这里有一个BUG。

FileChannel .transferTo 一次性最多只能发送2GB数据。也就是说单个文件大小超出2GB的话,需要多次发送。

类似于这样:

		@GetMapping("/download")
		public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

			// 下载的文件3.67 GB
			Path file = Paths.get("E:\\电影\\NothingtoLose\\NothingtoLose.mkv"); //

			String contentType = Files.probeContentType(file);
			if (contentType == null) {
				contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
			}

			try (FileChannel fileChannel = FileChannel.open(file)) {
				
				long size = fileChannel.size();
				
				log.info("文件大小: {}", size);

				response.setContentType(contentType);
				response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
						.filename(file.getFileName().toString(), StandardCharsets.UTF_8).build().toString());
				response.setContentLengthLong(size);

				/**
				 * transferTo 一次性最多只能处理2147483647字节数据。
				 * 所以需要多次调用
				 */
				
				long position = 0; 
				
				while (size > position) {
					long count = fileChannel.transferTo(position, size - position, Channels.newChannel(response.getOutputStream()));
					if (count > 0) {
						position += count;
					}
				}
			}
		}
1 个赞

我记得这个限制应该是操作系统给的吧

我在windows下也发现了这个问题。

都是有限制的,0拷贝依赖于操作系统提供的函数调用,只是不同系统限制的大小不一样,但都不是给你无限提供的。好像Windows限制的比Linux更小

1 个赞

这是因为Java中整型变量的最大值是2147483647,而FileChannel.transferTo方法的参数是一个long类型的值,但是底层操作系统接口(如sendfile)只支持int类型的值,因此Java将long类型的值转换为int类型的值,最大值即为2147483647。因此一次最多只能传输2147483647字节的数据。

chatGPT

1 个赞