package demo.io;
import java.io.*;
class 递归拷贝文件 {
public static void main(String[] args) throws IOException {
File file1 = new File("I:\\Test\\2");//源
File file2 = new File("I:\\22");//新目录
listCopyAll(file1, file2);//递归拷贝文件
}
//递归拷贝文件 file1 源目录,file2 新目录
private static void listCopyAll(File dir1, File dir2) throws IOException {
dir2.mkdir();//创建新目录
File[] files = dir1.listFiles();//获取源目录文件对象列表
for (File file : files) {//file源目录的最近一级子目录及文件
if (file.isDirectory()) {//如果是目录就继续遍历
//根据file传入new dir2子目录地址进行创建 listCopyAll中的两个参数同一水平
listCopyAll(file,new File(dir2.getAbsolutePath() + File.separator+ file.getName()));//在自身目录上衔接目录
} else {
//如果是文件就创建
File newFile = new File(dir2.getAbsolutePath() + File.separator+ file.getName());
newFile.createNewFile();
//拷贝文件
copyFile(file, newFile);
}
}
}
//copy文件
private static void copyFile(File file, File newFile) throws IOException {
//读取源文件信息
BufferedInputStream bufi = new BufferedInputStream(new FileInputStream(file));
//写入新文件信息
BufferedOutputStream bufo = new BufferedOutputStream(new FileOutputStream(newFile));
int len = 0;
byte[] buf = new byte[1024];
while ((len = bufi.read(buf)) != -1) {
bufo.write(buf,0,len);
bufo.flush();
}
bufi.close();
bufo.close();
}
}
Java递归拷贝文件
最新推荐文章于 2022-10-08 17:00:55 发布