Delete Files with same Prefix String using Java

前端 未结 11 1726
梦谈多话
梦谈多话 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条回答
  •  Happy的楠姐
    2020-12-16 10:08

    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() );
        }
    }
    

提交回复
热议问题