Java: Deleting files that start with a specific string.

Hey,

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.

Thanks,
Kate
kasiencjaAsked:
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());
    }
0
 
ksivananthCommented:
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
0
 
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.
0
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.

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

-----------------------------------------------------------------------------
import java.io.*;

public class dir {
      static private String[] files;
      static File dir=new File("./");
      
      public static void main(String[] args) {
            files=dir.list();
            for(int i=0;i<files.length;i++){
                  System.out.println(files[i]);
                  if(files[i].toString().matches("^l300.*|^300.*")){
                        File temp=new File(files[i]);
                        temp.delete();
                        System.out.println("Deleted: "+files[i]);
                  }
            }
      }
}
-----------------------------------------------------------------------------
0
 
mr_egyptianCommented:
That's for the current directory (./), and I guess the .toString() is unnecessary...
0
 
mr_egyptianCommented:
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.
0
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.