前言:对JavaSE学习回顾,使用File文件对象、字节流、递归(递归只是一种现象)拷贝源文件夹中所有文件、文件夹极其子文件夹下的文件和文件夹。
注意事项:递归操作容易出现内存溢出,所以操作的源文件夹目录层级不要太深!!!
以下为代码实现:
package cn.itcast.javaeeday11level01;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
*
* @author 大家都说名字长不会被发现
*
*/
public class CopyFolder {
public static void main(String[] args) throws FileNotFoundException {
File sourceFolder = new File("D:\\Java Android学习区\\教学视频\\数据结构");
File goalFolder = new File("D:\\CopyTest");
copyFolder(sourceFolder, goalFolder);
}
public static void copyFolder(File sourceFolder,File goalFolder) throws FileNotFoundException {
//判断目标文件夹是否存在
if (!goalFolder.exists()) {
//不存在创建一个目标文件夹
goalFolder.mkdir();
}
//判断源文件夹是否存在
if (sourceFolder.exists()) {
//获取源文件夹下文件夹及文件的File对象
File[] listFiles = sourceFolder.listFiles();
//遍历File文件数组
for (File file : listFiles) {
//判断是文件还是文件夹
if (file.isDirectory()) {
//是文件夹就创建一个新的File对象,将目标File对象和文件夹名传入
File newFileFolder = new File(goalFolder,file.getName());
//在目标文件夹下创建文件夹
newFileFolder.mkdir();
//递归调用方法自身
copyFolder(file, newFileFolder);
}else if (file.isAbsolute()) {
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
//定义新File对象
File newFile = new File(goalFolder,file.getName());
//定义字节输入输出流
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = new BufferedOutputStream(new FileOutputStream(newFile));
//定义字节数组,大小为1M
byte[] buffer = new byte[1024*1024];
int len;
while((len = inputStream.read(buffer)) !=-1) {
//读数据
inputStream.read(buffer, 0, len);
}
//将数据写入
outputStream.write(buffer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}else {
throw new FileNotFoundException("您输入的路径不存在,请您重新输入");
}
}
}