2013-06-24 81 views
0

这里有些事情我不明白。此代码删除了“东西”目录中的所有文件:File.delete()不会删除文件

public static void main(String[] args) throws Exception { 

    File dire = new File("C:\\Users\\spacitron\\Desktop\\Stuff"); 

    for (File doc : dire.listFiles()) { 
     doc.delete(); 
    } 

} 

但是,如果我尝试用它做什么有用的,比如只删除重复文件,它不会工作:

public static void main(String[] args) throws Exception { 

    File dire = new File("C:\\Users\\spacitron\\Desktop\\Stuff"); 
    ArrayList<String> hashes = new ArrayList<>(); 
    for (File doc : dire.listFiles()) { 
     String docHash = getHash(doc); 
     if (hashes.contains(docHash)) { 
      doc.delete(); 
     } else { 
      hashes.add(docHash); 
     } 
    } 

} 

public static String getHash(File d) { 
    MessageDigest md = null; 
    try { 
     md = MessageDigest.getInstance("SHA1"); 
     FileInputStream inStream = new FileInputStream(d); 
     DigestInputStream dis = new DigestInputStream(inStream, md); 
     BufferedInputStream bis = new BufferedInputStream(dis); 
     while (true) { 
      int b = bis.read(); 
      if (b == -1) 
       break; 
     } 
    } catch (NoSuchAlgorithmException | IOException e) { 
     e.printStackTrace(); 
    } 

    BigInteger bi = new BigInteger(md.digest()); 

    return bi.toString(16); 
} 

是什么赋予了?

+0

尝试关闭流? – Farlan

+1

你没有关闭输入流 –

+1

等于哈希!=等于文件,但!等于哈希==!相等文件....只是因为哈斯是相同的...并不意味着它是相同的文件。但如果哈希是不同的..文件是不同的 –

回答

2

您需要关闭在finally块将是最好的输入流,这些将要访问你的文件仍然防止它们被删除,因为他们都在使用

FileInputStream inStream = null; 
    DigestInputStream dis = null; 
    BufferedInputStream bis = null; 

    try { 
     md = MessageDigest.getInstance("SHA1"); 
     inStream = new FileInputStream(d); 
     dis = new DigestInputStream(inStream, md); 
     bis = new BufferedInputStream(dis); 
     while (true) { 
      int b = bis.read(); 
      if (b == -1) 
       break; 
      } 
    } catch (NoSuchAlgorithmException | IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try{ 
      if(inStream!= null) 
       inStream.close(); 
      if(dis != null) 
       dis.close(); 
      if(bis != null) 
       bis.close() 
     } catch (Exception ex){ 
      ex.printStackTrace() 
     }   
    } 
+0

哎,忘了那个。现在它工作了! – spacitron

+0

如果您有权访问Java 7(您在使用多捕获时似乎拥有这些功能),那么您应该使用try-with-resources,因为这会清理很多样板文件。如果其中一个调用close()引发异常,则此答案中发布的代码可能无法关闭某些流。 – ntoskrnl

+0

确实,忘记了这些,谢谢 –

2

的Windows不允许删除文件是开放的,除非它们用Java编程时不可用的特殊标志打开。虽然这个代码可以在Unix系统上工作,但在Windows上它不会。

关闭打开的文件通常是一个好主意,因为操作系统会限制应用程序在任何给定时间可以打开的文件数量。