Skip to content
Advertisement

Delete all files with an extension using Java

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

Advertisement

Answer

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());
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement