Sangeet Menon Sangeet Menon - 2 years ago 92
Java Question

Delete Files with same Prefix String using Java

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


The latter part of the file is the date of the file. (For eg.

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

File f=new File("dailyReport_08232011.txt");
catch(Exception e){

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

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 Source

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() {
    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() );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download