该程序可以将指定的文件夹及其子目录复制到指定路径下面去。
话不多说,直接上代码!
package com.IOtest;
import java.io.*;
/*
拷贝目录
*/
public class CopyAll {
public static void main(String[] args) {
//拷贝源
File srcFile = new File("E:\\vivado");
//目标
File destFile = new File("D:\\a\\b\\c");
//调用拷贝方法
copyDir(srcFile, destFile);
}
/**
* 拷贝目录
*
* @param srcFile 拷贝源
* @param destFile 拷贝目标
*/
private static void copyDir(File srcFile, File destFile) {
if (srcFile.isFile()) {
//srcFile如果是一个文件的话,递归结束
//一边读一边写
FileInputStream in = null;
FileOutputStream out = null;
try {
//读这个文件
in = new FileInputStream(srcFile);
//写到这个文件中
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" + srcFile.getAbsolutePath().substring(3));
out = new FileOutputStream(path);
//边读边写
byte[] bytes = new byte[1024 * 1024];//一次复制1M
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 (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//获取源下面的子目录
File[] files = srcFile.listFiles();
for (File file : files) {
//获取所有文件(包括目录和文件)的绝对路径
//System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
String srcDir = file.getAbsolutePath();
String desDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" + srcDir.substring(3));
File newFile = new File(desDir);
if (!newFile.exists()) {
newFile.mkdirs();
}
}
//递归调用
copyDir(file, destFile);
}
}
}
源文件:
运行之后结果:
所有字节一个不漏,复制完成!