这里有些事情我不明白。此代码删除了“东西”目录中的所有文件: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);
}
是什么赋予了?
尝试关闭流? – Farlan
你没有关闭输入流 –
等于哈希!=等于文件,但!等于哈希==!相等文件....只是因为哈斯是相同的...并不意味着它是相同的文件。但如果哈希是不同的..文件是不同的 –