加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:49:30 所属栏目:Java 来源:网络整理
导读:我(相对)是 Java的新手,我正在尝试实现一个运行命令列表的.jar,在Windows XP的命令提示符下它将是: cdcd myfolderdel *.lck /s 我的(失败)尝试: // Lists all files in folderFile folder = new File(dir);File fList[] = folder.listFiles();// Searchs
我(相对)是 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());
    }
}

我搞砸了“得到(i)”,但我觉得我现在非常接近我的目标.

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

编辑

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

// 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],因为fList是一个数组,它返回一个File引用而不是String.

变化: –

String pes = fList.get(i);

至: –

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读