用java写,复制某个目录及其包含的文件到指定的目录
时间: 2024-03-10 19:50:39 浏览: 66
可以使用Java的File类和递归函数来实现复制某个目录及其包含的文件到指定的目录。代码如下:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyDirectory {
public static void main(String[] args) {
String sourceDir = "C:/sourceDir"; // 源目录
String targetDir = "C:/targetDir"; // 目标目录
File source = new File(sourceDir);
File target = new File(targetDir);
try {
copyDirectory(source, target);
System.out.println("目录复制成功!");
} catch (IOException e) {
System.out.println("目录复制失败:" + e.getMessage());
}
}
public static void copyDirectory(File source, File target) throws IOException {
if (source.isDirectory()) {
if (!target.exists()) {
target.mkdirs();
}
String[] fileList = source.list();
for (String fileName : fileList) {
File srcFile = new File(source, fileName);
File destFile = new File(target, fileName);
copyDirectory(srcFile, destFile);
}
} else {
FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(target);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
}
}
```
在代码中,设置源目录和目标目录,并创建File对象。然后调用copyDirectory函数,该函数递归地遍历源目录下的所有文件和子目录,如果是目录则创建目录,并继续递归遍历该目录下的所有文件和子目录,如果是文件则进行复制操作。最后,在主函数中进行调用。
阅读全文
相关推荐
















