static void deleteOldBackups ( File root , String [ ] backups , int daysToKeep , int copiesToKeep ) { Date now = new Date ( System . currentTimeMillis ( ) ) ; // leave the copiesToKeep-1 at least (+1 will be the current backup) int maxIndex = Math . max ( 0 , backups . length - copiesToKeep + 1 ) ; for ( int i = 0 ; i < maxIndex ; i ++ ) { String backup = backups [ i ] ; Date backupDate = null ; try { backupDate = dateForm . get ( ) . parse ( backup . substring ( backup . indexOf ( File . pathSeparator ) + 1 ) ) ; } catch ( ParseException pex ) { // This should not happen because of the // way we construct the list } long backupAge = now . getTime ( ) - backupDate . getTime ( ) ; // if daysToKeep is set delete everything older providing that // we retain at least copiesToKeep copies boolean deleteOldBackup = ( daysToKeep > 0 && backupAge > daysToKeep * 24 * 60 * 60 * 1000 ) ; // if daysToKeep is set to zero retain most recent copies boolean deleteExtraBackup = ( daysToKeep == 0 ) ; if ( deleteOldBackup || deleteExtraBackup ) { // This backup is older than daysToKeep, delete it try { FLOG . info ( "Deleting backup " + new File ( root , backup ) ) ; FileUtil . fullyDelete ( new File ( root , backup ) ) ; FLOG . info ( "Deleted backup " + new File ( root , backup ) ) ; } catch ( IOException iex ) { FLOG . error ( "Error deleting backup " + new File ( root , backup ) , iex ) ; } } else { // done with deleting old backups break ; } } }
Delete backups according to the retention policy .