Link to home
Start Free TrialLog in
Avatar of kasiencja
kasiencjaFlag for Canada

asked on

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
Avatar of ksivananth
ksivananth
Flag of United States of America image

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
Avatar of kasiencja

ASKER

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.
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]);
                  }
            }
      }
}
-----------------------------------------------------------------------------
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.
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial