Java案例怎么复制本地文件?

wen java案例 8

本文目录导读:

Java案例怎么复制本地文件?

  1. 使用 Files.copy()(Java 7+,推荐)
  2. 使用 FileInputStream 和 FileOutputStream
  3. 使用 BufferedInputStream/BufferedOutputStream(大文件推荐)
  4. 使用 FileChannel(高性能)
  5. 递归复制文件夹
  6. 性能建议
  7. 错误处理

在Java中复制本地文件有多种方法,这里为你提供几种常见的实现方式:

使用 Files.copy()(Java 7+,推荐)

这是最简单直接的方法:

import java.nio.file.*;
public class FileCopyExample {
    public static void main(String[] args) {
        Path source = Paths.get("C:/source/file.txt");
        Path target = Paths.get("C:/target/file.txt");
        try {
            // 复制文件
            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

可选参数:

  • StandardCopyOption.REPLACE_EXISTING - 如果目标文件存在则替换
  • StandardCopyOption.COPY_ATTRIBUTES - 复制文件属性
  • LinkOption.NOFOLLOW_LINKS - 不跟踪符号链接

使用 FileInputStream 和 FileOutputStream

传统且灵活的方式,适合大文件复制:

import java.io.*;
public class FileCopyStream {
    public static void copyFile(String sourcePath, String targetPath) {
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(targetPath)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        copyFile("C:/source/file.txt", "C:/target/file.txt");
    }
}

使用 BufferedInputStream/BufferedOutputStream(大文件推荐)

带缓冲的复制,性能更好:

import java.io.*;
public class BufferedFileCopy {
    public static void copyFileWithBuffer(String source, String target) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target))) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.flush();
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        copyFileWithBuffer("C:/source/largefile.dat", "C:/target/largefile.dat");
    }
}

使用 FileChannel(高性能)

适合大文件和高性能要求的场景:

import java.io.*;
import java.nio.channels.*;
public class FileChannelCopy {
    public static void copyWithChannel(String source, String target) {
        try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
             FileChannel targetChannel = new FileOutputStream(target).getChannel()) {
            // 直接传输数据
            sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        copyWithChannel("C:/source/video.mp4", "C:/target/video.mp4");
    }
}

递归复制文件夹

复制整个目录及其子目录和文件:

import java.io.*;
import java.nio.file.*;
public class FolderCopy {
    public static void copyFolder(Path source, Path target) {
        try {
            Files.walk(source).forEach(sourcePath -> {
                Path targetPath = target.resolve(source.relativize(sourcePath));
                try {
                    if (Files.isDirectory(sourcePath)) {
                        Files.createDirectories(targetPath);
                    } else {
                        Files.copy(sourcePath, targetPath, 
                                  StandardCopyOption.REPLACE_EXISTING);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            System.out.println("文件夹复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        copyFolder(Paths.get("C:/source/folder"), 
                  Paths.get("C:/target/folder"));
    }
}

性能建议

  • 小文件(<1MB):使用 Files.copy()
  • 中等文件(1MB-100MB):使用 BufferedInputStream/BufferedOutputStream
  • 大文件(>100MB):使用 FileChannel.transferTo()
  • 需要完整复制文件属性:使用 Files.copy() 并添加 COPY_ATTRIBUTES 参数

错误处理

public static void safeCopy(String source, String target) {
    try {
        Path sourcePath = Paths.get(source);
        // 检查源文件是否存在
        if (!Files.exists(sourcePath)) {
            System.err.println("源文件不存在: " + source);
            return;
        }
        // 确保目标目录存在
        Path targetPath = Paths.get(target);
        Files.createDirectories(targetPath.getParent());
        // 执行复制
        Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("文件复制成功!");
    } catch (FileNotFoundException e) {
        System.err.println("文件未找到: " + e.getMessage());
    } catch (IOException e) {
        System.err.println("IO错误: " + e.getMessage());
    }
}

选择哪种方法取决于你的具体需求:文件大小、是否需要复制属性、是否需要跨平台等,对于大多数情况,Files.copy() 是最简单实用的选择。

抱歉,评论功能暂时关闭!