使用零拷貝對檔案高效的切片和合並
阿新 • • 發佈:2020-07-01
使用零拷貝對檔案高效的切片和合並
對檔案的切片/合併在應用中是一個很常見的需求,使用 FileChannel
的 transferTo
/ 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); } } } }