0

这里发生了一些我不明白的事情。此代码删除“stuff”目录中的所有文件:

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);
}

是什么赋予了?

4

2 回答 2

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()
      }         
    }
于 2013-06-24T12:56:22.263 回答
2

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

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

于 2013-06-24T12:57:03.157 回答