复制多级文件夹,关键是在判断该目录是文件还是文件夹。如果是文件夹继续获取其中的文件,判读是否是文件夹........
这就要用递归了,分别把拷贝和检查文件夹写成两个方法,检查文件夹方法嵌套调用其本身继续检查。
package cn.kang03;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
*
* @author Administrator
*
*/
public class CopyAll {
public static void main(String[] args) {
// 封装目录
File srcfile = new File("C:\\Users\\admin\\Desktop\\A\\");// 源文件
File destfile = new File("C:\\Users\\admin\\Desktop\\B");// 目标文件
// 判断目标文件夹是否存在,不存在就创建
if (!destfile.exists()) {
destfile.mkdir();
System.out.println("目标文件夹创建成功!");
} else {
System.out.println("目标文件夹已存在!");
}
try {
CheckFolder(srcfile, destfile);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Copy Success!");
}
/**
* 复制文件,把srcfile中的文件复制到destfile
*
* @param srcfile
* 源文件
* @param destfile
* 目标文件
* @throws IOException
*/
public static void Copy(File srcfile, File destfile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcfile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destfile));
// 一次读取1024个字节
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(len);
bos.flush();// 刷新
}
// 关闭流,先开后关
bos.close();
bis.close();
}
/**
* 检查当前目录下是否有文件夹,有则把子目录文件夹中文件取出(复制多级文件夹)
*
* @param upfolder
* 当前目录
* @param downfolder
* 子目录
* @throws IOException
*/
public static void CheckFolder(File upfolder, File downfolder) throws IOException {
// 把源文件夹子目录的文件夹中所有文件放到数组中
File[] f = upfolder.listFiles();
for (File oldfile : f) {
System.out.println(oldfile);
if (oldfile.isDirectory()) {
// 如果是文件夹就在目标文件夹中创建一个文件夹
File newdestfile = new File(downfolder, oldfile.getName());// 创建目标文件路径
newdestfile.mkdir();// 在目标文件夹这个创建文件夹
// 递归,检查是否是文件夹
CheckFolder(oldfile, newdestfile);
} else {
// 如果不是文件夹就拷贝
File newfile = new File(downfolder, oldfile.getName());
Copy(oldfile, newfile);
}
}
}
}