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
My (failed) attempt:
// 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 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!
EDIT
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());
}
}
And now it works!
2022 version:
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;
}
fList.get(i)should befList[i]asfListis an array, and it returns aFilereference not aString.Change: –
to: –
And then change
if (pes.contains(".lck") == true)toif (pes.getName().contains(".lck"))In fact, since you are checking for the
extension, you should useendsWithmethod rather thancontainsmethod. And yes, you don’t need to compare yourbooleanvalue with==. So just use this condition: –