用文件字节流和File类实现目录的拷贝:
将:C:\Users\win10\Desktop\Photos
拷贝到:F:\
提示:
用到的类FileInputStream,FileOutputStream,File。
用到的思想:递归。
测试代码:
import java.io.*;
public class Test02 {
public static void main(String[] args) {
File srcFile = new File("C:\\Users\\win10\\Desktop\\Photos");
File destFile = new File("F:\\");
Test02.myCopy(srcFile, destFile);
}
// 递归读目录
public static void myCopy(File srcFile, File destFile) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (srcFile.isFile()) {
//System.out.println(srcFile.getName());
// srcFile是个文件,那就在目标处创建一个同名文件
String destPath = destFile.getAbsolutePath();
destPath = destPath.endsWith("\\") ? destPath : destPath + "\\";
File dest = new File(destPath + srcFile.getName() );
if (!dest.exists()) {
dest.createNewFile();
}
System.out.println(dest);
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(dest);
// 开始读写
byte[] bytes = new byte[1024 * 1024]; // 缓冲区为1MB
int readCount = 0;
while ((readCount = fis.read(bytes)) != -1) {
fos.write(bytes, 0, readCount);
}
// 输出完毕后刷新
fos.flush();
return; // 递归结束
// 注意:try..catch中会先执行finally再执行try中的return语句
}
// 程序执行到这里,说明srcFile是个目录,在目标处创建一个同名目录
//System.out.println(srcFile.getName());
String destPath = destFile.getAbsolutePath();
destPath = destPath.endsWith("\\") ? destPath : destPath + "\\";
File destDir = new File(destPath + srcFile.getName());
if (!destDir.exists()) {
destDir.mkdir();
}
System.out.println(destDir);
// 拷贝完目录后,拷贝目录的子文件
File[] files = srcFile.listFiles();
for (File f : files) {
myCopy(f, destDir);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入输出流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}