仅使用File,FileInputStream,FileOutputStream三个类库实现文件夹内所有内容的字节流拷贝
import java.io.*;
public class copy03 {
public static void main(String[] args) {
//拷贝源
File srcFile = new File("C:\\Users\\peanut\\Desktop\\实训\\python实训");
//拷贝目录
File destFile = new File("D:\\");
//调用拷贝函数
copyDir(srcFile,destFile);
}
private static void copyDir(File srcFile, File destFile) {
//判断,如果是个文件就无法递归,递归结束
if(srcFile.isFile()){
//创建输入输出流
FileInputStream in = null;
FileOutputStream out = null;
try {
//读操作对象
in = new FileInputStream(srcFile);
//字符串拼接出新文件的绝对路径放入字符串
String newPath = destFile.getAbsolutePath() + srcFile.getAbsolutePath().substring(27);
//写操作对象
out = new FileOutputStream(newPath);
//开始读写操作
//创建数组进行读写,一次复制1MB
byte[] bytes = new byte[1024*1024];
//记录读取数目
int readCount = 0;
//开始复制文件
while((readCount = in.read(bytes)) != -1){
out.write(bytes,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in == null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out == null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//获取子目录
File[] files = srcFile.listFiles();
//递归调用查找子目录
for (File file:files) {
//新建对应的目录
if(file.isDirectory()){
//目标目录与源目录进行字符串拼接,得到新的目标目录
String srcDir = file.getAbsolutePath();//源路径
String desDir = destFile.getAbsolutePath() + srcDir.substring(27);//源路径截取前27个字符拼接到目标路径之后
//创建新目录的file对象
File newfile = new File(desDir);
//判断此目录是否存在
if(!newfile.exists()){
newfile.mkdirs();
}
}
copyDir(file,destFile);
}
}
}
难点:子目录的拷贝采用了递归的思想,以及实现目标目录的绝对地址如何拼接起来。
总结:代码编写过程中多多进行测试,方便提前发现错误并改正。