1 使用到知识点:
文件夹创建
文件字节流拷贝
递归
2 代码
package com.bjsxt.io.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyDirCopy {
/**
*
*/
public static void main(String[] args) {
String srcPath = "D:/father/son1"; // 将 son1和son1下的所有内容拷贝到 son2/下
String destPath = "D:/father/son2";
if(srcPath.contains(destPath)){
System.out.println("孩子不能将父亲拷贝到其体内去");
return;
}
File srcFile = new File(srcPath);
File destFile = new File(destPath);
// 递归加拷贝
if(srcFile.isDirectory()) {
// 构建拷贝后的目标文件夹位置
destFile = new File(destFile, srcFile.getName());
//System.out.println(destFile.getName() + " : " + destFile.getAbsolutePath() ); // son1 D:\father\son2\son1
}
try {
copyDetails(srcFile,destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyDetails(File srcFile, File destFile) throws IOException {
if(srcFile.isFile()){
copyFile(srcFile,destFile);
}else if(srcFile.isDirectory()){
destFile.mkdirs();
File[] files = srcFile.listFiles();
for(File sub : files){
copyDetails(sub,new File(destFile,sub.getName()));
}
}
}
// 文件之间拷贝
private static void copyFile(File srcFile, File destFile) throws IOException {
if(destFile.isDirectory()){
System.out.println(destFile.getAbsolutePath()+"不能建立于文件夹同名的文件");
throw new IOException(destFile.getAbsolutePath()+"不能建立于文件夹同名的文件");
}
int len = 0;
byte[] buf = new byte[1024];
InputStream fis = new FileInputStream(srcFile);
OutputStream fos = new FileOutputStream(destFile);
while(-1 != (len=fis.read(buf))){
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
fis.close();
}
}
3 图: