How to filter Java Streams using Files.getAttribute

I am trying to filter files that were created more recent than another file. I just don't get how to apply the methods from Files directly to the stream.

Is there a neater way to do it?, I know it does not help readability to use Streams for the application but Im trying to learn to use it.

try (Stream<Path> stream = Files.walk(dir,1)) {
                res = stream.filter(Files::isDirectory).filter(
                     f->Files.getAttribute(f,"creationTime")>
                     Files.getAttribute(reference, "creationTime"))
                    .collect(Collectors.toList());
}

Upvotes: 0

Views: 337

Answers (1)

DuncG
DuncG

Reputation: 15196

You cannot compare a "creationTime" / FileTime with ">". If you view source of Files.isDirectory(path) and Files.getAttribute(path,attr) you will see that both read the underlying filesystem attributes - so two filters are re-reading similar definitions.

Switching to Files.find provides a much neater way to scan as it retrieves file attributes automatically and passes both the filesystem path and attribute to a bi-predicate. This makes it easier to pre-filter a Files.find stream firstly on directory and then by comparing the creation times using built-in time1.isAfter(time2). Something like this:

Instant refTime = Files.readAttributes(reference, BasicFileAttributes.class).creationTime().toInstant();
try(var dirs = Files.find(dir, 1 /*depth*/, (p,a) -> 
         a.isDirectory() && a.creationTime().toInstant().isAfter(refTime))) {
    List<Path> recentDirs = dirs.collect(Collectors.toList());
    ...
}

Upvotes: 4

Related Questions