DateTimeUtils { public static Predicate<File> getFilterForFilesOlderThanGivenDays(final long days) { final Instant maxAge = Instant.now(Clock.systemUTC()).minus(days, DAYS); return file -> { boolean canDelete = false; try { final Instant lastModifiedTime = Files.getLastModifiedTime(file.toPath()).toInstant(); canDelete = lastModifiedTime.isBefore(maxAge); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Can not determine last modification time", e); } return canDelete; }; }  static Instant toInstant(final LocalDateTime dateTime); static int sortByFileTime(final File file1, final File file2); static Predicate<File> getFilterForFilesOlderThanGivenDays(final long days);  }
@Test public void testFilesToDeleteOlderThan15Days() { final List<File> filesToDelete = Arrays.stream(TEMP_DIRECTORY.listFiles()) .filter(file -> file.getName().startsWith(TEMP_FILE_PREFIX)) .filter(DateTimeUtils.getFilterForFilesOlderThanGivenDays(15)) .collect(Collectors.toList()); assertNotNull(filesToDelete); assertFalse(filesToDelete.isEmpty()); assertEquals(1, filesToDelete.size()); assertEquals(file_15_daysOld, filesToDelete.get(0)); }
@Test public void testFilesToDeleteOlderThan10Days() throws IOException { final List<File> filesToDelete = Arrays.stream(TEMP_DIRECTORY.listFiles()) .filter(file -> file.getName().startsWith(TEMP_FILE_PREFIX)) .filter(DateTimeUtils.getFilterForFilesOlderThanGivenDays(10)) .sorted(DateTimeUtils::sortByFileTime) .collect(Collectors.toList()); assertNotNull(filesToDelete); assertFalse(filesToDelete.isEmpty()); assertEquals(2, filesToDelete.size(), filesToDelete.toString()); assertEquals(file_15_daysOld, filesToDelete.get(0)); assertEquals(file_10_daysOld, filesToDelete.get(1)); }