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
for (File f : folder.listFiles()) {
if (f.getName().endsWith(".lck")) {
f.delete(); // may fail mysteriously - returns boolean you may want to check
}
}
Java 8 approach
Arrays.stream(yourDir.listFiles((f, p) -> p.endsWith("YOUR_FILE_EXTENSION"))).forEach(File::delete);
fList.get(i)
should be fList[i]
as fList
is an array, and it returns a File
reference not a String
.
Change: -
String pes = fList.get(i);
to: -
File pes = fList[i];
And then change if (pes.contains(".lck") == true)
to
if (pes.getName().contains(".lck"))
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());
}
You are using Collection
method get
on an Array
. Use Array Index
notation as below:
File pes = fList[i];
Also better to use endsWith() String method over the file name as:
if (pes.getName().endsWith(".lck")){
...
}
Final Code which works :)
File folder = new File(dir);
File fList[] = folder.listFiles();
for (File f : fList) {
if (f.getName().endsWith(".png")) {
f.delete();
}}