java 把一个文件夹的文件复制到另一个文件夹中
时间: 2023-08-05 14:06:33 浏览: 48
你可以使用 Java 的文件操作类 File 和 IO 流来实现文件夹中文件的复制。以下是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileCopyUtil {
public static void copyFolder(File sourceFolder, File destFolder) throws IOException {
if (!destFolder.exists()) {
destFolder.mkdir();
}
File[] files = sourceFolder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
File newFolder = new File(destFolder, file.getName());
copyFolder(file, newFolder);
} else {
File newFile = new File(destFolder, file.getName());
copyFile(file, newFile);
}
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile);
FileChannel sourceChannel = fis.getChannel();
FileChannel destChannel = fos.getChannel()) {
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}
}
}
```
你可以使用以下代码调用上述方法:
```java
File sourceFolder = new File("path/to/source/folder");
File destFolder = new File("path/to/destination/folder");
FileCopyUtil.copyFolder(sourceFolder, destFolder);
```
将 `path/to/source/folder` 替换为要复制的源文件夹路径,将 `path/to/destination/folder` 替换为要复制到的目标文件夹路径。