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

我(相对)是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) to
if (pes.getName().contains(".lck"))

实际上,由于您要检查extension ,因此应使用endsWith方法而不是contains方法。 是的,您不需要将您的boolean值与==进行比较。 所以只要使用这个条件: –

 if (pes.getName().endsWith(".lck")) { boolean success = (new File(fList.get(i)).delete()); } 
 for (File f : folder.listFiles()) { if (f.getName().endsWith(".lck")) { f.delete(); // may fail mysteriously - returns boolean you may want to check } } 

Java 8方法

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

最终代码有效:)

 File folder = new File(dir); File fList[] = folder.listFiles(); for (File f : fList) { if (f.getName().endsWith(".png")) { f.delete(); }} 

您正在使用Collection方法get Array 。 使用Array Index表示法如下:

  File pes = fList[i]; 

最好在文件名上使用endsWith() String方法:

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