package Io流.File的学习;
import java.io.*;
import java.util.Arrays;
public class 拷贝目录demo {
public static void main(String[] args) throws IOException {
createFile("src/Io流/File的学习/需要拷贝文件夹", "src/Io流/File的学习/指定文件夹");
}
/**
* 递归拷贝文件夹及其下所有文件
*
* @param filePath1 源文件夹路径
* @param filePath2 目标文件夹路径
*/
public static void createFile(String filePath1, String filePath2) {
// 创建源文件夹对象
File file = new File(filePath1);
// 获取源文件夹下的所有文件和文件夹
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.isDirectory()) { // 如果是文件夹,则递归复制文件夹及其内容
filePath2 = filePath2 + "/" + file1.getName();
File file2 = new File(filePath2);
// 如果目标文件夹不存在,则创建该文件夹
if (!file2.exists()) {
file2.mkdirs();
}
createFile(file1.getPath(), file2.getPath());
} else { // 如果是文件,则复制文件
File file_root = new File(filePath2);
// 如果目标文件夹不存在,则创建该文件夹
if (!file_root.exists()) {
file_root.mkdirs();
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file1);
fos = new FileOutputStream(filePath2 + "/" + file1.getName());
byte[] bytes = new byte[1024];
int readAccounts = 0;
// 读取源文件并将数据写入目标文件
while ((readAccounts = fis.read(bytes)) != -1) {
fos.write(bytes, 0, readAccounts);
}
// 刷新缓冲区
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入流和输出流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
简单的Java文集拷贝Demo
猜你喜欢
转载自blog.csdn.net/lfeishumomol/article/details/131849230
今日推荐
周排行