2014-12-04 57 views
1

我想寫一個程序,它將刪除目錄中的所有重複文件。它目前能夠檢測到重複,但我的刪除代碼似乎並沒有工作(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); 
       } 
      } 
     } 
    } 
} 
+1

在'if(isDuplicate(files [i],files [j]))'你爲什麼重新創建一個文件對象?只要刪除其中一個重複項,例如'files [i] .delete()' – Athafoud 2014-12-04 18:49:39

+0

幫你一個忙,並使用java.nio.file。如果文件刪除失敗,至少會引發異常... – fge 2014-12-04 18:50:38

回答

3

你閉上你的文件流?如果文件當前處於打開狀態,它將會返回false,這是有道理的。

3

除了資源問題(這當然解釋了爲什麼你不能刪除),問題是你不知道爲什麼刪除失敗 - 事實上,你根本無法知道。

下面是對應的程序編寫與java.nio.file,與資源管理:

public final class Duplicates 
{ 

    private Duplicates() 
    { 
     throw new Error("nice try!"); 
    } 

    private static boolean duplicate(final Path path1, final Path path2) 
     throws IOException 
    { 
     if (Files.isSameFile(path1, path2)) 
      return true; 

     final BasicFileAttributeView view1 
      = Files.getFileAttributeView(path1, BasicFileAttributeView.class); 
     final BasicFileAttributeView view2 
      = Files.getFileAttributeView(path2, BasicFileAttributeView.class); 

     final long size1 = view1.readAttributes().size(); 
     final long size2 = view2.readAttributes().size(); 

     if (size1 != size2) 
      return false; 
     try (
      final FileChannel channel1 = FileChannel.open(path1, 
       StandardOpenOption.READ); 
      final FileChannel channel2 = FileChannel.open(path2, 
       StandardOpenOption.READ); 
     ) { 
      final ByteBuffer buf1 
       = channel1.map(FileChannel.MapMode.READ_ONLY, 0L, size1); 
      final ByteBuffer buf2 
       = channel2.map(FileChannel.MapMode.READ_ONLY, 0L, size1); 

      // Yes, this works; see javadoc for ByteBuffer.equals() 
      return buf1.equals(buf2); 
     } 
    } 

    public static void main(final String... args) 
     throws IOException 
    { 
     final Path dir = Paths.get(System.getProperty("user.dir")); 
     final List<Path> list = new ArrayList<>(); 

     for (final Path entry: Files.newDirectoryStream(dir)) 
      if (Files.isRegularFile(entry)) 
       list.add(entry); 

     final int size = list.size(); 

     for (int i = 0; i < size; i++) 
      for (int j = i + 1; j < size; j++) 
       try { 
        if (duplicate(list.get(i), list.get(j))) 
         Files.deleteIfExists(list.get(j)); 
       } catch (IOException e) { 
        System.out.printf("Aiie... Failed to delete %s\nCause:\n%s\n", 
         list.get(j), e); 
       } 
    } 
} 

注:一個更好的策略很可能會創建一個目錄中,你會打動你檢測所有副本;完成後,只需刪除此目錄中的所有文件,然後刪除目錄本身。見Files.move()