1. 使用 FileInputStream 和 FileOutputStream

这是最传统的方法,使用字节流进行文件复制。这种方法简单直观,但在大数据量下可能效率较低。

示例代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyStream {
    public static void main(String[] args) {
        String sourcePath = "path/to/source/file.txt";
        String destPath = "path/to/destination/file.txt";
        
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(destPath)) {
            
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用 BufferedInputStream 和 BufferedOutputStream 为了提高效率,可以在 FileInputStream 和 FileOutputStream 上添加缓冲区。这可以显著减少磁盘访问次数,从而提高复制速度。 示例代码:
import java.io.*;

public class FileCopyBuffered {
    public static void main(String[] args) {
        String sourcePath = "path/to/source/file.txt";
        String destPath = "path/to/destination/file.txt";
        
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))) {
            
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.Files.copy()方法

示例代码:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileCopyNIO {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("path/to/source/file.txt");
        Path destPath = Paths.get("path/to/destination/file.txt");
        
        try {
            Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}