Delete Files with same Prefix String using Java

Sangeet Menon picture Sangeet Menon · Aug 30, 2011 · Viewed 51.2k times · Source

I have around 500 text files inside a directory with a same prefix in their filename say dailyReport_.

The latter part of the file is the date of the file. (For eg. dailyReport_08262011.txt, dailyReport_08232011.txt)

I want to delete these files using a Java procedure (I could go for a shell script and add it a job in the crontab but the application is meant to used by laymen).

I can delete one single file using something like this

        try{
          File f=new File("dailyReport_08232011.txt");
          f.delete();
        }
        catch(Exception e){ 
                System.out.println(e);
        }

but can I delete the files having a certain prefix (eg: dailyReport08 for the 8th month ) I could easily do that in shell script by using rm -rf dailyReport08*.txt .

But File f=new File("dailyReport_08*.txt"); doesnt work in Java (as expected).

Now is any thing as such possible in Java without running a loop that searches the directory for files?

Can I achieve this using some special characters similar to * used in shell script?

Answer

BegemoT picture BegemoT · Aug 30, 2011

No, you can't. Java is rather low-level language -- comparing with shell-script -- so things like this must be done more explicetly. You should search for files with required mask with folder.listFiles(FilenameFilter), and iterate through returned array deleting each entry. Like this:

final File folder = ...
final File[] files = folder.listFiles( new FilenameFilter() {
    @Override
    public boolean accept( final File dir,
                           final String name ) {
        return name.matches( "dailyReport_08.*\\.txt" );
    }
} );
for ( final File file : files ) {
    if ( !file.delete() ) {
        System.err.println( "Can't remove " + file.getAbsolutePath() );
    }
}