Directory stream with Java 8 lambda
Short snippet how to leave 100 newest text files in directory and delete others with help of Java 8 lambda.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
String pattern = "**.txt"; int fileCapacity = 100; Path path = Paths.get("your/directory/"); PathMatcher ldfMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); try (DirectoryStream files = Files.newDirectoryStream(path)) { StreamSupport.stream(files.spliterator(), false) // sequential stream .filter(file -> Files.isRegularFile(file) && ldfMatcher.matches(file)) .sorted((Path o1, Path o2) -> { try { return Files.getLastModifiedTime(o2).compareTo(Files.getLastModifiedTime(o1)); } catch (IOException ex) { // exception handling... } }) .skip(fileCapacity) .forEach(file -> { try { Files.delete(file); } catch (IOException ex) { // exception handling... } }); } catch (IOException ex) { // exception handling... } |
I love it when folks come together and share opinions, great site, keep it up.
Way cool, some valid points! I appreciate you making this article available, the rest of the site is also high quality.
Have a fun.
Respect to website author , some wonderful entropy.