package cn.java.io.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Demo09 {
public static void dirsCopy(File srcPath,File destPath){
File copyPath = destPath;
if(srcPath.isDirectory()){
//如果是文件夹,则创建新的文件夹关联。此关联用于在目标文件夹下创建与源文件夹同名的文件夹目录
copyPath = new File(destPath,srcPath.getName());
}
//在目标文件夹下创建与源文件夹同名的文件夹目录
copyPath.mkdirs();
try {
//将文件夹内文件进行逐个拷贝
fileDatilCopy(srcPath,copyPath);
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读写失败");
e.printStackTrace();
}
}
private static void fileDatilCopy(File srcPath,File copyPath) throws FileNotFoundException, IOException {
if(srcPath.isFile()){ //如果源文件是文件而非文件夹
try {
//调用fileCopy()方法对文件进行拷贝
fileCopy(srcPath,copyPath);
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读写失败");
e.printStackTrace();
}
}else if(srcPath.isDirectory()){//如果源文件夹是文件而非文件
//确保目标文件夹存在
copyPath.mkdirs();
//获取下一级目录|文件
for(File sub:srcPath.listFiles()){
fileDatilCopy(sub,new File(copyPath,sub.getName()));
}
}
}
public static void fileCopy(File srcPath,File srcCopy) throws FileNotFoundException,IOException {
//选择文件输入流
InputStream is = new FileInputStream(srcPath);
//选择文件输出流
OutputStream out = new FileOutputStream(srcCopy,true);
byte[] by = new byte[100000];
int len = 0;
while(is.read(by)!= -1){
//读多少写多少,防止资源浪费
out.write(by,0,len);
}
//flush()方法强制刷出
out.flush();
//先打开后关闭原则,关闭流
out.close();
is.close();
}
public static void main(String[] args) {
//原路径
File srcPath = new File("D:/myCode/temp");
//指定路径
File destPath = new File("D:/myCode/Temp_1");
dirsCopy(srcPath,destPath);
}
}