练习要求:
- 实现复制源文件srcFile到目标文件destFile。
- 复制文件夹,使用递归将文件夹中的文件复制到目标文件夹下。
实现效果
查看文件数量是否相同
思路
- 编写复制文件的方法copyFile
-编写复制文件夹的方法,srcFile.listFiles()获取文件夹下的所有字文件数组
-循环判断是否为文件:是,调用copyFile 否 调用copyFolder实现递归遍历文件夹下的所有文件
package iotest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TestCopy {
public static void main(String[] args) {
String srcPath = "D:\\Program Files\\7-Zip";
String destPath = "D:\\temp\\t\\";
// copyFile(srcPath,destPath);
copyFolder(srcPath,destPath);
}
private static void copyFolder(String srcPath, String destPath) {
File srcFile = new File(srcPath);
File[] files = srcFile.listFiles();
for (File file : files) {
if (file.isFile()) {
File destFile = new File(destPath+file.getPath().split(":")[1]);
copyFile(file.getAbsolutePath(), destFile.getParent()+File.separator);
}else {
copyFolder(file.getAbsolutePath(), destPath);
}
}
}
/**
* 复制文件
* @param srcPath
* @param destPath
*/
private static void copyFile(String srcPath,String destPath) {
File srcFile = new File(srcPath);
File destFile = new File(destPath+srcFile.getName());
// 文件夹不存在时创建文件夹
if (!destFile.getParentFile().exists()) {
boolean result = destFile.getParentFile().mkdirs();
if (result) {
System.out.println(destFile.getParentFile()+"创建成功");
}else {
System.out.println(destFile.getParentFile()+"创建失败");
}
}
try(
BufferedReader br = new BufferedReader(new FileReader(srcFile));
PrintWriter pw = new PrintWriter(new FileWriter(destFile));
){
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
System.out.println(destFile.getAbsolutePath()+" 复制成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
想看电影关注我的公众号:电影资源集(支持输入电影名称自动回复了)
![]()