gpt4 book ai didi

java - 无法删除给定目录中的文件

转载 作者:行者123 更新时间:2023-11-29 07:00:17 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来删除目录中的所有重复文件。它目前能够检测到重复项,但我的删除代码似乎不起作用(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);
}
}
}
}
}

最佳答案

您是否关闭了文件流?如果文件当前打开,它会返回 false 是有道理的。

关于java - 无法删除给定目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com