java将一个文件夹下面的子文件夹拷贝到另一个路径下面
时间: 2023-12-04 07:04:44 浏览: 59
你可以使用 Java 的文件操作类 File 来实现文件夹的拷贝。具体实现步骤如下:
1. 定义两个 File 类型的对象,分别表示源文件夹和目标文件夹。
```
File sourceFolder = new File("源文件夹路径");
File targetFolder = new File("目标文件夹路径");
```
2. 判断源文件夹是否存在,如果不存在则无法进行拷贝。
```
if (!sourceFolder.exists()) {
System.out.println("源文件夹不存在");
return;
}
```
3. 创建目标文件夹。如果目标文件夹已经存在,则无需创建。
```
if (!targetFolder.exists()) {
targetFolder.mkdir();
}
```
4. 遍历源文件夹下的所有子文件夹,将每个子文件夹拷贝到目标文件夹下。
```
File[] subFolders = sourceFolder.listFiles(File::isDirectory);
for (File subFolder : subFolders) {
String subFolderName = subFolder.getName();
File targetSubFolder = new File(targetFolder, subFolderName);
targetSubFolder.mkdir(); // 创建目标子文件夹
copyFolder(subFolder, targetSubFolder); // 递归拷贝子文件夹
}
```
5. 如果源文件夹下还有子文件夹,则递归拷贝子文件夹。
```
private static void copyFolder(File sourceFolder, File targetFolder) {
File[] files = sourceFolder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
String subFolderName = file.getName();
File targetSubFolder = new File(targetFolder, subFolderName);
targetSubFolder.mkdir();
copyFolder(file, targetSubFolder);
} else {
File targetFile = new File(targetFolder, file.getName());
try (InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
完整代码如下所示:
```
import java.io.*;
public class CopyFolderDemo {
public static void main(String[] args) {
File sourceFolder = new File("源文件夹路径");
File targetFolder = new File("目标文件夹路径");
if (!sourceFolder.exists()) {
System.out.println("源文件夹不存在");
return;
}
if (!targetFolder.exists()) {
targetFolder.mkdir();
}
File[] subFolders = sourceFolder.listFiles(File::isDirectory);
for (File subFolder : subFolders) {
String subFolderName = subFolder.getName();
File targetSubFolder = new File(targetFolder, subFolderName);
targetSubFolder.mkdir();
copyFolder(subFolder, targetSubFolder);
}
}
private static void copyFolder(File sourceFolder, File targetFolder) {
File[] files = sourceFolder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
String subFolderName = file.getName();
File targetSubFolder = new File(targetFolder, subFolderName);
targetSubFolder.mkdir();
copyFolder(file, targetSubFolder);
} else {
File targetFile = new File(targetFolder, file.getName());
try (InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
注意,上述代码中的 "源文件夹路径" 和 "目标文件夹路径" 需要替换成实际的文件夹路径。
阅读全文