一、步骤
-1. 创建对象表示要拷贝的数据源
File src = new File("表示要拷贝数据源的路径");
-2. 创建对象表示拷贝数据的目的地
File dest = new File("表示数据将要拷贝到的目的地");
-3. 调用方法进行拷贝
copydir(参数一,参数二);
参数一:表示要拷贝数据源的路径
参数二:表示数据将要拷贝到的目的地
-代码演示
public static void main(String[] args) throws IOException {
//拷贝一个文件夹,考虑子文件
//1.创建对象表示数据源
File src = new File("E:\\test\\src");
//2.创建对象表示目的地
File dest = new File("E:\\test\\dest");
//3.调用方法开始拷贝
copydir(src,dest);
}
/*
作用:拷贝文件夹
参数一:要拷贝的数据源
参数二:拷贝数据的目的地
*/
private static void copydir(File src, File dest) throws IOException {
dest.mkdirs();
//递归
//1.进入数据源
File[] files = src.listFiles();
//2.遍历数组,得到的file依次表示数据源文件中的每一个文件和文件夹
for (File file : files) {
//判断当前的file是文件还是文件夹,如果是文件则进行拷贝,反之则进行递归
if(file.isFile()){
//3.判断文件进行拷贝
//创建输入流对象,将源文件中的数据读取到程序中
FileInputStream fis = new FileInputStream(file);
//创建输出流对象,将程序中读取到的数据写入拷贝文件的目的地
FileOutputStream fos = new FileOutputStream(new File(dest,file.getName()));
//创建一个1024的字节数组用来拷贝数据
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();
}else {
//4.判断文件夹,递归
copydir(file,new File(dest,file.getName()));
}
}
}