When using SftpFileSystem (NIO), calling Files.readAttributes() or Files.size() triggers a remote network call, which is expensive. Standard Java FileVisitor implementations are also slow because they call readAttributes() for every file.
To list files and attributes efficiently, you have two options:
- Use
SftpClient directly: Use client.readDir() to get DirEntry objects, which contain both the filename and the attributes in a single request. - Cast to
SftpPath: If using DirectoryStream<Path>, the returned Path objects are often SftpPath instances. You can cast them to SftpPath to access cached attributes without a new network call.
Warning: Attributes are a snapshot from the time the directory was listed. They do not reflect subsequent changes to the files.
// Efficient way using SftpPath cache
try (DirectoryStream<Path> dir = Files.newDirectoryStream(directoryPath)) {
for (Path path : dir) {
if (path instanceof SftpPath) {
SftpClient.Attributes attributes = ((SftpPath) path).getAttributes();
process.accept(path, attributes);
}
}
}