Java复制文件到另一个文件夹
时间: 2024-01-01 08:03:17 浏览: 75
以下是Java实现文件夹内所有文件拷贝到另一个文件夹的代码示例:
```java
import java.io.*;
public class CopyFolder {
public static void main(String[] args) {
File srcFolder = new File("source folder path");
File destFolder = new File("destination folder path");
// 如果目标文件夹不存在,则创建
if (!destFolder.exists()) {
destFolder.mkdir();
System.out.println("Destination folder created successfully");
}
// 获取源文件夹下的所有文件和文件夹
File[] files = srcFolder.listFiles();
// 遍历所有文件和文件夹
for (File file : files) {
// 如果是文件,则直接拷贝
if (file.isFile()) {
File destFile = new File(destFolder, file.getName());
copyFile(file, destFile);
}
// 如果是文件夹,则递归调用本方法
else if (file.isDirectory()) {
File newDestFolder = new File(destFolder, file.getName());
newDestFolder.mkdir();
copyFolder(file, newDestFolder);
}
}
System.out.println("Copy completed successfully");
}
// 拷贝文件
private static void copyFile(File srcFile, File destFile) {
try (InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 拷贝文件夹
private static void copyFolder(File srcFolder, File destFolder) {
if (!destFolder.exists()) {
destFolder.mkdir();
}
File[] files = srcFolder.listFiles();
for (File file : files) {
if (file.isFile()) {
File destFile = new File(destFolder, file.getName());
copyFile(file, destFile);
} else if (file.isDirectory()) {
File newDestFolder = new File(destFolder, file.getName());
newDestFolder.mkdir();
copyFolder(file, newDestFolder);
}
}
}
}
```
请注意,上述代码中的“source folder path”和“destination folder path”需要替换为实际的源文件夹路径和目标文件夹路径。
阅读全文