1. 目的
将 E:\IOTest\day21_IO_test路径下的所有东西 复制到 E:\tohere\copyall 目录下
2.效果
3.代码
package cn.ma.IOTest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 复制多极文件夹
* 分析:
* 1.封装路径
* 数据源 E:\IOTest\day21_IO_test
* 目的地 E:\tohere\copyall
* 2. 复制文件夹
* 调用方法 将 数据源 及 目的路径作为参数进行传递
* 3. 复制 文件
*
*
*/
public class IOTest6 {
public static void main(String[] args) throws IOException {
//1. 封装数据源
File src = new File("E:\\IOTest\\day21_IO_test");
// 2. 封装目的地 路径
File target = new File("E:\\tohere\\copyall");
copyfolder(src,target);//调用复制文件夹的方法
}
/**
*2. 复制文件夹 递归的思想
*/
public static void copyfolder(File src, File target) throws IOException {
if(src.isDirectory()){//如果是文件夹
File newFilePath = new File(target, src.getName());//目标文件夹 及 新文件的名字 组成 新的文件
newFilePath.mkdir();//造 新的一层文件夹
// 获取该File对象下的所有文件或者文件夹File对象
File[] files = src.listFiles();
for (File file : files) {
copyfolder(file, newFilePath);
}
}else{
File newfile = new File(target, src.getName());
copyfile(src,newfile);
}
}
/**
* 3. 复制文件
*/
public static void copyfile(File src, File newfile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newfile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}