以下是一个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
来复制文件,这是一个相对高效的方式来处理文件复制,因为它允许使用更少的内存并可能利用操作系统的特定功能来优化复制操作。