1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class FileCopyDemo {
public static void main(String[] args) throws Exception { Path source = Paths.get("path/to/source/file"); Path target = Paths.get("path/to/target/file"); long fileSize = Files.size(source); if (fileSize <= 5 * 1024 * 1024) { zeroCopyFile(source, target); } else { aioCopyFile(source, target, fileSize); } }
private static void zeroCopyFile(Path source, Path target) throws IOException { try (FileChannel sourceChannel = new FileInputStream(source.toFile()).getChannel(); FileChannel targetChannel = new FileOutputStream(target.toFile()).getChannel()) { sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); } }
private static void aioCopyFile(Path source, Path target, long fileSize) throws Exception { try (AsynchronousFileChannel sourceChannel = AsynchronousFileChannel.open(source, StandardOpenOption.READ); AsynchronousFileChannel targetChannel = AsynchronousFileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024); futureAIOCopy(sourceChannel, targetChannel, buffer, 0, fileSize); } }
private static void futureAIOCopy(AsynchronousFileChannel sourceChannel, AsynchronousFileChannel targetChannel, ByteBuffer buffer, long position, long fileSize) throws Exception { if (position >= fileSize) { return; } buffer.clear(); Future<Integer> operation = sourceChannel.read(buffer, position); Integer bytesRead = operation.get(); if (bytesRead > 0) { buffer.flip(); targetChannel.write(buffer, position).get(); futureAIOCopy(sourceChannel, targetChannel, buffer, position + bytesRead, fileSize); } } }
|