import java.io.*;
public class CopyFolderDemo2 {
public static void main(String[] args) throws IOException {
//创建数据源File对象
File srcFile = new File(“E:\itcast”);
//创建目的地File对象
File destFile = new File(“F:\”);
copyFolder(srcFile,destFile);
}
public static void copyFolder(File srcFile,File destFile) throws IOException {
if(srcFile.isDirectory()){
//在目的地下创建和数据源File名称一样的目录
String srcFileName = srcFile.getName();
File newFolder = new File(destFile,srcFileName);
if(!newFolder.exists()){
newFolder.mkdir();
}
File[] fileArray = srcFile.listFiles();
//遍历该File数组,得到每一个File对象
for(File file:fileArray){
copyFolder(file,newFolder);
}
}else{
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile,newFile);
}
}
public static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
//复制数据
byte[] bys = new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys);
}
//释放资源
bos.close();
bis.close();
}
}