Use java to delete all files with extensions

I'm (relatively) new to Java and I'm trying to implement a to run a command list Jar, at the command prompt of Windows XP, it will 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 up get (I), but I think I'm very close to my goal now

I ask for your help. Thank you very much!

edit

well! Thank you very much Through three suggested modifications, I finally get:

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

Now it works!

Solution

fList. Get (I) should be flist [i], because flist is an array that returns a file reference instead of a string

Change: –

String pes = fList.get(i);

To: –

File pes = fList[i];

Then change if (PES. Contains (". Lck") = = true) to if (PES. Getname() contains(“.lck”))

In fact, since you want to check the extension, you should use the endswith method instead of the contains method Yes, you do not need to compare your Boolean with = = So just use this condition: –

if (pes.getName().endsWith(".lck")) {
    boolean success = (new File(fList.get(i)).delete());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>