Last active
June 24, 2021 01:23
-
-
Save rodrigocananea/f62cef9825d91736e02e4998edb0f833 to your computer and use it in GitHub Desktop.
Java 8 Limit files by last modified (.sql / .zip)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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