public static void deleteFilesWithFileFilter ( final File source , final FileFilter includeFileFilter , final FileFilter excludeFileFilter ) throws FileIsNotADirectoryException , IOException , FileIsSecurityRestrictedException { if ( ! source . isDirectory ( ) ) { throw new FileIsNotADirectoryException ( "Source file '" + source . getAbsolutePath ( ) + "' is not a directory." ) ; } File [ ] includeFilesArray ; if ( null != includeFileFilter ) { includeFilesArray = source . listFiles ( includeFileFilter ) ; } else { includeFilesArray = source . listFiles ( ) ; } if ( null != includeFilesArray ) { File [ ] excludeFilesArray = null ; List < File > excludeFilesList = null ; if ( null != excludeFileFilter ) { excludeFilesArray = source . listFiles ( excludeFileFilter ) ; excludeFilesList = Arrays . asList ( excludeFilesArray ) ; } // if excludeFilesList is not null and not empty if ( null != excludeFilesList && ! excludeFilesList . isEmpty ( ) ) { for ( final File element : includeFilesArray ) { final File currentFile = element ; // if the excludeFilesList does not contain the current file do copy... if ( ! excludeFilesList . contains ( currentFile ) ) { if ( currentFile . isDirectory ( ) ) { // delete directory recursive... deleteFilesWithFileFilter ( currentFile , includeFileFilter , excludeFileFilter ) ; } else { // delete file deleteFile ( currentFile ) ; } } // otherwise do not delete the current file... } } else { // otherwise delete all files and directories for ( final File currentFile : includeFilesArray ) { if ( currentFile . isDirectory ( ) ) { // delete directory recursive... deleteFilesWithFileFilter ( currentFile , includeFileFilter , excludeFileFilter ) ; } else { // delete file deleteFile ( currentFile ) ; } } } } else { throw new FileIsSecurityRestrictedException ( "File '" + source . getAbsolutePath ( ) + "' is security restricted." ) ; } }
Tries to delete all files that match to the given includeFileFilter and does not delete the files that match the excludeFileFilter from the given source directory .