import java.io.*;
public class Test {
public static void main(String[] args) {
File srcFile = new File("D:/Netease");
File destFile = new File("D:/test");
copyDir(srcFile, destFile);
}
/**
* 拷贝目录
* @param srcFile 起始目录
* @param destFile 目标目录
*/
private static void copyDir(File srcFile, File destFile) {
if (srcFile.isFile()){
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
String s = destFile.getAbsoluteFile() + (destFile.getAbsolutePath().endsWith("/") ? srcFile.getAbsolutePath().substring(3) : srcFile.getAbsolutePath().substring(2));
File file = new File(s);
File file1 = new File(file.getParent());
if(!file1.exists()){
file1.mkdirs();
}
out = new FileOutputStream(s);
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 (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 destDir = destFile.getAbsoluteFile() + (destFile.getAbsolutePath().endsWith("/") ? srcDir.substring(3) : srcDir.substring(2));
// System.out.println(destDir);
File file1 = new File(destDir);
if (!file1.exists()){
file1.mkdirs();
}
}
copyDir(file, destFile);
}
}
}