我们先来看一下什么是递归式复制
递归式复制指的是当要复制的目录下 存在子目录,且子目录中存在子目录或文件的时候,将逐一复制它们。windows的复制默认是这样的。如果不递归复制,结果你得到的目录只包含空的子目录,其子目录下的内容将不会复制。
import java.io.*;
@SuppressWarnings({"all"})
public class Test {
public static void main(String[] args) {
String oldPathName = "D:\\IDEAprojects\\file_test\\sd";
String newPathName = "D:\\IDEAprojects\\file_test\\aa";
recursiveCopy(oldPathName, newPathName);
}
/**
* @param oldPathName 源文件或文件夹的地址
* @param newPathName 目的文件或文件夹的地址
*/
public static void recursiveCopy(String oldPathName, String newPathName) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
File file = new File(oldPathName);
File newFile = new File(newPathName);
if (!newFile.exists()) {
if (file.isFile()) {
try {
newFile.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (file.isDirectory()) {
newFile.mkdirs();
}
}
try {
//创建输入输出流
int readLen = 0;
byte[] b = new byte[1024];
System.out.println(file.exists());
if (file.exists()) {
if (file.isDirectory()) {
//listFiles()返回目录里的文件的file对象
File[] childrenFiles = file.listFiles();
for (Object o : childrenFiles) {
File childrenFile = (File) o;
recursiveCopy(childrenFile.getAbsolutePath(), newPathName + "//" + childrenFile.getName());
}
}
//如下,就可以理解为边界条件
if (file.isFile()) {
fileInputStream = new FileInputStream(oldPathName);
fileOutputStream = new FileOutputStream(newPathName);
while ((readLen = fileInputStream.read(b)) != -1) {
fileOutputStream.write(b, 0, readLen);
}
fileOutputStream.close();
fileInputStream.close();
return;
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}