目錄拷貝
import java.io.*;
/**
* 目錄拷貝
*/
public class CopyAll {
public static void main(String[] args) {
File srcFile = new File("D:\\StudySource\\Java\\powernode\\文本筆記");
File destFile = new File("F:\\Java 目錄拷貝\\");
copyAll(srcFile, destFile);
}
private static void copyAll(File srcFile, File destFile) {
if (srcFile.isFile()) {
// 是文件,遞歸結束,開始拷貝
FileInputStream in = null;
FileOutputStream out = null;
try {
// in = new FileInputStream(srcFile.getAbsoluteFile());
// 或者這么寫
in = new FileInputStream(srcFile);
byte[] bytes = new byte[1024 * 1024];
out = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ?
destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )
+ srcFile.getAbsolutePath().substring(3));
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 f : files) {
if (f.isDirectory()){
String srcDir = f.getAbsolutePath(); // 原文件絕對路徑
String srcDir2 = srcDir.substring(3); //截掉前面的盤符
// 這里是因為有時候復制到 F:\\ 和 F:\\a\\b\\ 下讀取的絕對路徑不一樣
String destDir = (destFile.getAbsolutePath().endsWith("\\") ?
destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )
+ srcDir2;
// 新建一個 File 對象
File newFile = new File(destDir);
// 目錄不存在,則以多重目錄的方式新建目錄
if (!newFile.exists()){
newFile.mkdirs();
}
}
// 遞歸
copyAll(f, destFile);
}
}
}