我想寫一個程序,它將刪除目錄中的所有重複文件。它目前能夠檢測到重複,但我的刪除代碼似乎並沒有工作(Files.delete()
返回false
)。有人可以告訴我爲什麼這是嗎?無法刪除給定目錄中的文件
當前代碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.SecurityManager;
public class Duplicate {
@SuppressWarnings("resource")
public static boolean isDuplicate(File a, File b) throws IOException {
FileInputStream as = new FileInputStream(a);
FileInputStream bs = new FileInputStream(b);
while(true) {
int aBytes = as.read();
int bBytes = bs.read();
if(aBytes != bBytes) {
return false;
} else if(aBytes == -1) {
System.out.println("Duplicate found: "+a.getName()+", "+b.getName());
return true;
}
}
}
public static void main(String[] args) throws IOException {
File dir = new File(System.getProperty("user.dir"));
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
for(int j = i+1; j < files.length; j++) {
if(isDuplicate(files[i], files[j])) {
String filePath = System.getProperty("user.dir").replace("\\", "/")+"/"+files[i].getName();
System.out.println("Deleting "+filePath);
File f = new File(filePath);
if(f.delete())
System.out.println(filePath+" deleted successfully");
else
System.out.println("Could not delete "+filePath);
}
}
}
}
}
在'if(isDuplicate(files [i],files [j]))'你爲什麼重新創建一個文件對象?只要刪除其中一個重複項,例如'files [i] .delete()' – Athafoud 2014-12-04 18:49:39
幫你一個忙,並使用java.nio.file。如果文件刪除失敗,至少會引發異常... – fge 2014-12-04 18:50:38