使用IO流复制文件夹

11 篇文章 0 订阅

以下是一个Java程序,使用IO流递归地复制一个文件夹及其所有子文件夹和文件到另一个位置。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class RecursiveFolderCopy {
    public static void copyFolder(File source, File dest) throws IOException {
        if (source.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String[] children = source.list();
            for (String child : children) {
                copyFolder(new File(source, child), new File(dest, child));
            }
        } else {
            copyFile(source, dest);
        }
    }
    private static void copyFile(File sourceFile, File destFile) throws IOException {
        try (
            FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
            FileChannel destChannel = new FileOutputStream(destFile).getChannel();
        ) {
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        }
    }
    public static void main(String[] args) {
        try {
            File sourceFolder = new File("path/to/source/folder");
            File destFolder = new File("path/to/destination/folder");
            copyFolder(sourceFolder, destFolder);
            System.out.println("Folder copied recursively successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个程序中,copyFolder 方法是递归的。它首先检查源是否是一个目录。如果是,它会创建目标目录(如果尚不存在),然后递归地复制源目录中的每个子目录或文件。如果源是一个文件,它会调用 copyFile 方法来复制文件。 请将 "path/to/source/folder" 和 "path/to/destination/folder" 替换为你需要复制的源文件夹和目标文件夹的实际路径。 这个程序使用了 FileChannel 来复制文件,这是一个相对高效的方式来处理文件复制,因为它允许使用更少的内存并可能利用操作系统的特定功能来优化复制操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值