IO流-复制多极文件夹(递归实现)

时间:2023-03-10 01:53:08
IO流-复制多极文件夹(递归实现)
package com.io.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; /*
* 复制多极文件夹
* 数据源: F:\\Demo
* 目的地: D:\\demo
*
* 分析:
* A:封装数据源
* B:封装目的地
* C:获取该File对象下所有的文件夹或文件
* 遍历每一个File对象
* D:判断是否是文件夹或文件
* 是文件夹:
* 就在目的地目录下创建该文件夹File
* 回到C
*
* 是文件:
* 直接复制
*/
public class Test07_标准版 {
public static void main(String[] args) throws IOException {
File srcFolder=new File("f:\\Demo");
File destFolder=new File("d:\\demo");
if(!destFolder.exists()){
destFolder.mkdir();
}
copyFolder(srcFolder,destFolder);
}
//复制文件夹
public static void copyFolder(File srcFolder, File destFolder) throws IOException {
File[] listFiles = srcFolder.listFiles();
for(File f:listFiles){
if(f.isDirectory()){
//创建新的目录 File newFolder=new File(destFolder,f.getName());
newFolder.mkdir();
copyFolder(f,newFolder); }else{
//复制文件
File newFile=new File(destFolder,f.getName());
copyFile(f,newFile);
}
}
}
//复制文件
public static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(newFile));
int len=0;
byte[] buf=new byte[1024];
while((len=bis.read(buf))!=-1){
bos.write(buf, 0, len);
bos.flush();
}
bis.close();
bos.close();
}
}