java 复制文件夹下所有文件夹和文件
时间: 2023-08-30 13:06:06 浏览: 48
java文件复制,实现文件的复制
可以使用递归的方式来实现文件夹下所有文件和文件夹的复制。
以下是一个简单的 Java 代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFolder {
public static void main(String[] args) {
String sourceFolder = "source_folder_path";
String destinationFolder = "destination_folder_path";
File source = new File(sourceFolder);
File destination = new File(destinationFolder);
try {
copyFolder(source, destination);
System.out.println("Folder copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyFolder(File source, File destination) throws IOException {
if (source.isDirectory()) {
if (!destination.exists()) {
destination.mkdir();
}
String[] files = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
} else {
FileInputStream inputStream = new FileInputStream(source);
FileOutputStream outputStream = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
}
```
以上代码会将 `source_folder_path` 文件夹下的所有文件和文件夹复制到 `destination_folder_path` 文件夹下。如果目标文件夹不存在,代码中会自动创建。
阅读全文