I'm writing a backup program using Java and the package NIO.
As far as I found, I could do it as in the code example below, i.e. read the folder content list and then for each file I have to do file attributes request... this is not an effective approach, especially if someone has big folders with thousands of files there in one folder, so maybe there is another way to do it by reading folder's content with all its attributes?
Or maybe should I use something else instead of NIO for this case? Thank You very much
public void scan(Path folder) throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(folder)) {
for (Path path : ds) {
//Map<String, Object> attributes = Files.readAttributes(path, "size,lastModifiedTime");
}
}
}
Thanks to DuncG, the answer is very simple:
HashMap <Path, BasicFileAttributes> attrs = new HashMap<>();
BiPredicate<Path, BasicFileAttributes> predicate = (p, a) -> {
return attrs.put(p, a) == null;
};
Stream<Path> stream = Files.find(folder, Integer.MAX_VALUE, predicate);
I made a benchmark to compare, this example executes 3x times faster than the example from the question text, so it seems that it invokes fewer filesystem I/O operations... in theory...