boolean flag = false;
File srcFile = new File(srcPath);
if (!srcFile.exists() || !srcFile.isDirectory()) { // 源文件夾不存在
return false;
}
//獲得待復制的文件夾的名字,比如待復制的文件夾為"E://dir//"則獲取的名字為"dir"
String dirName = srcFile.getName();
//目標文件夾的完整路徑
String destDirPath = destDir + File.separator + dirName + File.separator;
File destDirFile = new File(destDirPath);
if(destDirFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) {
return false;
}
if(destDirFile.exists() && destDirFile.isDirectory() && !overwriteExistDir) { // 目標位置有一個同名文件夾且不允許覆蓋同名文件夾,則直接返回false
return false;
}
if(!destDirFile.exists() && !destDirFile.mkdirs()) { // 如果目標目錄不存在并且創建目錄失敗
return false;
}
File[] fileList = srcFile.listFiles(); //獲取源文件夾下的子文件和子文件夾
if(fileList.length==0) { // 如果源文件夾為空目錄則直接設置flag為true,這一步非常隱蔽,debug了很久
flag = true;
}
else {
for(File temp: fileList) {
if(temp.isFile()) { // 文件
flag = copyFile(temp.getAbsolutePath(), destDirPath, overwriteExistDir); // 遞歸復制時也繼承覆蓋屬性
}
else if(temp.isDirectory()) { // 文件夾
flag = copyDirectory(temp.getAbsolutePath(), destDirPath, overwriteExistDir); // 遞歸復制時也繼承覆蓋屬性
}
if(!flag) {
break;
}
}
}
return flag;
}
/**
* 刪除文件或文件夾
* @param path
* 待刪除的文件的絕對路徑
* @return boolean
*/
public static boolean deleteFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) { // 文件不存在直接返回
return flag;
}
flag = file.delete();
return flag;
}
/**
* 由上面方法延伸出剪切方法:復制+刪除
* @param destDir 同上
*/
public static boolean cutGeneralFile(String srcPath, String destDir) {
boolean flag = false;
if(copyGeneralFile(srcPath, destDir) && deleteFile(srcPath)) { // 復制和刪除都成功
flag = true;
}
return flag;
}
public static void main(String[] args) {
/** 測試復制文件 */
System.out.println(copyGeneralFile("d://test/test.html", "d://test/test/")); // 一般正常場景
System.out.println(copyGeneralFile("d://notexistfile", "d://test/")); // 復制不存在的文件或文件夾
System.out.println(copyGeneralFile("d://test/test.html", "d://test/")); // 待復制文件與目標文件在同一目錄下
System.out.println(copyGeneralFile("d://test/test.html", "d://test/test/")); // 覆蓋目標目錄下的同名文件
System.out.println(copyFile("d://test/", "d://test2", false)); // 不覆蓋目標目錄下的同名文件
System.out.println(copyGeneralFile("d://test/test.html", "notexist://noexistdir/")); // 復制文件到一個不可能存在也不可能創建的目錄下
System.out.println("---------");
/** 測試復制文件夾 */
System.out.println(copyGeneralFile("d://test/", "d://test2/"));
System.out.println("---------");
/** 測試刪除文件 */
System.out.println(deleteFile("d://a/"));
}
}
新聞熱點
疑難解答