- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
-
- public class FileCopy {
- public static void main(String[] args) {
- String sourceFilePath = "source.txt";
- String targetFilePath = "target.txt";
-
- try (FileInputStream inputStream = new FileInputStream(sourceFilePath);
- FileOutputStream outputStream = new FileOutputStream(targetFilePath)) {
-
- byte[] buffer = new byte[4096];
- int bytesRead;
-
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, bytesRead);
- }
-
- System.out.println("文件拷贝完成");
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- import java.io.IOException;
- import java.nio.channels.FileChannel;
- import java.nio.file.Path;
- import java.nio.file.Paths;
-
- public class FileCopy {
- public static void main(String[] args) {
- String sourceFilePath = "source.txt";
- String targetFilePath = "target.txt";
-
- Path sourcePath = Paths.get(sourceFilePath);
- Path targetPath = Paths.get(targetFilePath);
-
- try (FileChannel sourceChannel = FileChannel.open(sourcePath);
- FileChannel targetChannel = FileChannel.open(targetPath)) {
-
- long transferredBytes = sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
-
- System.out.println("文件拷贝完成,已传输 " + transferredBytes + " 字节");
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Java 标准类库本身已经提供了 Files.copy 的实现。
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
-
- public class FileCopy {
- public static void main(String[] args) {
- String sourceFilePath = "source.txt";
- String targetFilePath = "target.txt";
-
- Path sourcePath = Paths.get(sourceFilePath);
- Path targetPath = Paths.get(targetFilePath);
-
- try {
- Files.copy(sourcePath, targetPath);
- System.out.println("文件拷贝完成");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
零拷贝(Zero-Copy)是一种优化文件复制操作的技术,它通过减少数据在内核空间和用户空间之间的传输次数来提高性能。