使用Java删除所有具有扩展名的文件

10

我(相对而言)对Java还很陌生,我试图实现一个可以运行一系列命令的.jar文件,在Windows XP的命令提示符中可以这样写:

cd\
cd myfolder
del *.lck /s

我的(失败的)尝试:

// Lists all files in folder
File folder = new File(dir);
File fList[] = folder.listFiles();
// Searchs .lck
for (int i = 0; i < fList.length; i++) {
    String pes = fList.get(i);
    if (pes.contains(".lck") == true) {
        // and deletes
        boolean success = (new File(fList.get(i)).delete());
    }
}

我在那个“get(i)”附近搞砸了,但我认为我离我的目标非常接近了。

我请求您的帮助,在此先行致谢!


编辑

好的!非常感谢大家。经过三次建议的修改,我最终得到了:

// Lists all files in folder
File folder = new File(dir);
File fList[] = folder.listFiles();
// Searchs .lck
for (int i = 0; i < fList.length; i++) {
    String pes = fList[i];
    if (pes.endsWith(".lck")) {
        // and deletes
        boolean success = (new File(fList[i]).delete());
    }
}

现在它可以工作了!

2022版本:

public static boolean deleteAllFilesWithSpecificExtension(String pathToDir, String extension) {
        boolean success = false;
        File folder = new File(pathToDir);
        File[] fList = folder.listFiles();
        for (File file : fList) {
            String pes = file.getName();
            if (pes.endsWith("." + extension)) {
                success = (new File(String.valueOf(file)).delete());
            }
        }
        return success;
    }

数组没有 get 方法,这意味着 fList.get(i) 无法编译。相反,要访问数组中的对象 i,请使用 fList[i] - FThompson
1
可以将“pes.contains(".lck")”改为“pes.endsWith(".lck")”,这样会更好。 - Alexandre Lavoie
1
你应该使用endsWith(...)而不是contains(...),除非你也想删除类似myfile.lck.exe这样的文件。 - Jon Newmuis
谢谢。建议越接近我写的那三行命令,越好~ - user1869316
6个回答

12
for (File f : folder.listFiles()) {
    if (f.getName().endsWith(".lck")) {
        f.delete(); // may fail mysteriously - returns boolean you may want to check
    }
}

7

fList.get(i) 应该改为 fList[i],因为 fList 是一个数组,它返回的是 File 引用而不是 String

更改为:-

String pes = fList.get(i);

to: -

File pes = fList[i];

然后将if (pes.contains(".lck") == true)更改为
if (pes.getName().contains(".lck"))

实际上,由于您正在检查文件的扩展名,因此应该使用endsWith方法而不是contains方法。是的,您不需要将您的布尔值与==进行比较。所以只需使用此条件:-

if (pes.getName().endsWith(".lck")) {
    boolean success = (new File(fList.get(i)).delete());
}

5

Java 8方法

Arrays.stream(yourDir.listFiles((f, p) -> p.endsWith("YOUR_FILE_EXTENSION"))).forEach(File::delete);    

3

最终可用的代码 :)

File folder = new File(dir);
                File fList[] = folder.listFiles();

                for (File f : fList) {
                    if (f.getName().endsWith(".png")) {
                        f.delete(); 
                    }}

0

您正在使用Collection方法get来操作一个Array。请使用以下的Array Index表示法:

        File pes = fList[i];

同时最好使用 endsWith() 字符串方法而不是文件名:

   if (pes.getName().endsWith(".lck")){
      ...
   }

0

Java 8 lambda

File folder = new File(yourDirString);
Arrays.stream(folder.listFiles())
            .filter(f -> f.getName().endsWith(".lck"))
            .forEach(File::delete);

你能在你的回答中增加更多的解释吗?为什么你的代码片段可以帮助OP解决他们的问题? - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接