import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class homeWork2 {
public static void main(String[] args) throws IOException {
File file = new File("D:/a");
File file2 = new File("D:/b");
copyMove(file, file2);
}
// 把一个文件目录所有东西复制到另一个位置
static int count = 0;
// 先判断吗目标文件夹是否存在,如果存在继续判断,如果不存在则创造
public static void copyMove(File sor , File des){
if (!des.exists()) {
des.mkdirs(); // 首先判断目标目录是否为空
}
File[] ls = sor.listFiles(); // 创建sor文件对象数组
if (ls != null) { // 非空判断
for (File file : ls) { // 增强for循环sor对象数组
if (file.isFile()) { // 判断sor数组对象file是否为file文件类型
// String string = file2.getAbsolutePath() + file.separator +file.getName();
File file3 = new File(des, file.getName()); // 创建新文件对象 父类赋值des ,child赋值file的名字调用getname
// System.out.println(file3);
copyOfText(file, file3); // 调用io流读取输入实行文件传输
} if (file.isDirectory()) { // 判断是否是文件夹
// 新建个对象,路径则需获得des的绝对路径和sor文件夹的名字然后用全局常量separator进行拼接
File file3 = new File(des.getAbsolutePath() +File.separator + file.getName() );
file3.mkdirs(); // 创建文件
copyMove(file, file3); // 持续递归
}
}
}
}
private static void copyOfText(File file, File file2) {
try (
FileInputStream fis = new FileInputStream(file); // 创建字节输入流
FileOutputStream fio = new FileOutputStream(file2); // 创建字节输出流
) {
byte bt[] = new byte[1024]; // 创建一个byte数组用来装输入流
int count;
while ((count = fis.read(bt)) != -1) {
fio.write(bt, 0, count); // write写出
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}