使用Java删除所有带扩展名的文件 [英] Delete all files with an extension using Java

查看:110
本文介绍了使用Java删除所有带扩展名的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(相对)是Java的新手,我正在尝试实现一个运行命令列表的.jar,它在Windows XP的命令提示符下会是:

I'm (relatively) new to Java and I'm trying to implement a .jar that runs a list of commands that in Windows XP's command prompt it would be:

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)附近搞砸了,但我认为我现在非常接近我的目标。

I screwed somewhere around that "get(i)", but I think I'm pretty close to my goal now.

我请求你的帮助,并提前非常感谢你!

I ask for your help and thank you very much in advance!

编辑

好吧!非常感谢大家。通过3个建议的修改,我最终得到:

Alright! Many thanks, everybody. With the 3 suggested modifications I ended up with:

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

现在可行了!

推荐答案

fList.get(i)应为 fList [i] as fList 是一个数组,它返回文件引用而不是字符串

fList.get(i) should be fList[i] as fList is an array, and it returns a File reference not a String.

更改: -

String pes = fList.get(i);

to: -

File pes = fList[i];

然后更改 if(pes.contains(。lck)=如果(pes.getName()。contains(。lck))

事实上,既然你要检查扩展名,你应该使用 endsWith 方法而不是包含方法。是的,您不需要将布尔值与 == 进行比较。所以只需使用这个条件: -

In fact, since you are checking for the extension, you should use endsWith method rather than contains method. And yes, you don't need to compare your boolean value with ==. So just use this condition: -

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

这篇关于使用Java删除所有带扩展名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆