gpt4 book ai didi

java - 如何递归复制整个目录,包括Java中的父文件夹

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:36 24 4
gpt4 key购买 nike

我目前正在将文件夹从一个地方复制到另一个地方。它工作正常,但它没有复制所有其他文件和文件夹所在的原始文件夹。这是我正在使用的代码:

public static void copyFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest+"\\"+src.getName(), file);
//recursive copy
copyFolder(srcFile,destFile);
}
} else {
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}

所以我有文件夹 src C:\test\mytest\..all folders..

我想把它复制到C:\test\myfiles

但不是获取 C:\test\myfiles\mytest\..all folders.. 我获取 C:\test\myfiles\..all folders..

最佳答案

尝试使用 copyDirectory(File srcDir, File destDir)来自 Apache Commons IO 的方法取而代之的是图书馆。

关于java - 如何递归复制整个目录,包括Java中的父文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11651900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com