Skip to content

Instantly share code, notes, and snippets.

@rodrigocananea
Last active June 24, 2021 01:23
Show Gist options
  • Save rodrigocananea/f62cef9825d91736e02e4998edb0f833 to your computer and use it in GitHub Desktop.
Save rodrigocananea/f62cef9825d91736e02e4998edb0f833 to your computer and use it in GitHub Desktop.
Java 8 Limit files by last modified (.sql / .zip)
// Days of limit
final int limitDays = 5;
List<File> files = Files.list(Paths.get("D:\Backup"))
.filter(Files::isRegularFile) // only files
.filter(path -> path.toString().endsWith(".zip")
|| path.toString().endsWith(".sql"))
// convert to milliseconds and compare
.filter(path -> LocalDateTime.ofInstant(Instant.ofEpochMilli(path.toFile().lastModified()),
TimeZone.getDefault().toZoneId()).toInstant(ZoneOffset.UTC).toEpochMilli()
< LocalDateTime.now().minusDays(limitDays).toInstant(ZoneOffset.UTC).toEpochMilli())
.map(Path::toFile)
.sorted(Comparator.comparingLong(File::lastModified))
.collect(Collectors.toList());
files.forEach(f -> {
System.out.println("# Deleting file: " + f.getPath());
f.delete();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment