Java: Deleting files that start with a specific string.


What would be the most efficient way of deleting files from a directory that start with a specific string.   For example:

String startString = “300”;

Than all files that start with 300 and l300 (that's lower "L" and 300) will be deleted.

Who is Participating?
rrzConnect With a Mentor Commented:
Try something like  
    FilenameFilter deleteFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("300") || name.startsWith("l300");
    File dir = new File(pathToDirectory);
    File[] dFiles = dir.listFiles(deleteFilter);
    for(int i =0; i< dFiles.length;i++){
            if(dFiles[i].delete()) System.out.println(dFiles[i].getName() + " was deleted");
              else System.out.println("could not delete " + dFiles[i].getName());
1. get the list of all files from the dir
2. loop through each file and check the file name starts with the string or 'l' + string
3. true --> delete it
4. false --> continue
kasiencjaAuthor Commented:
I was hoping I could use something like FilenameFilterEx, however through trial and error I found out that the filter only works for file extensions.
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

I tested this and it seems to do what you're asking:


public class dir {
      static private String[] files;
      static File dir=new File("./");
      public static void main(String[] args) {
            for(int i=0;i<files.length;i++){
                        File temp=new File(files[i]);
                        System.out.println("Deleted: "+files[i]);
That's for the current directory (./), and I guess the .toString() is unnecessary...
I didn't really think about why you would want to do this, but it would be much more efficient to weite a shell (or batch) script to do this at the os level.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.