Delete Files with same Prefix String using Java

前端 未结 11 1742
梦谈多话
梦谈多话 2020-12-16 09:11

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 fi

11条回答
  •  生来不讨喜
    2020-12-16 10:05

    I agree with BegemoT.

    However, just one optimization: If you need a simple FilenameFilter, there is a class in the Google packages. So, in this case you do not even have to create your own anonymous class.

    import com.google.common.io.PatternFilenameFilter;
    
    final File folder = ...
    final File[] files = folder.listFiles(new PatternFilenameFilter("dailyReport_08.*\\.txt"));
    
    // loop through the files
    for ( final File file : files ) {
        if ( !file.delete() ) {
            System.err.println( "Can't remove " + file.getAbsolutePath() );
        }
    }
    

    Enjoy !

提交回复
热议问题