Skip to content

Commit

Permalink
[FS] Using try-with-resources with Files.list() in local listFolders (o…
Browse files Browse the repository at this point in the history
  • Loading branch information
chaohengstudent authored Jun 12, 2023
1 parent f9d6ced commit 985d4e3
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions fs/src/main/java/org/astraea/fs/local/LocalFileSystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.astraea.common.Configuration;
import org.astraea.common.Utils;
import org.astraea.fs.FileSystem;
Expand Down Expand Up @@ -73,17 +72,23 @@ public synchronized List<String> listFolders(String path) {
private synchronized List<String> listFolders(String path, boolean requireFile) {
var folder = resolvePath(path);
if (!Files.isDirectory(folder)) throw new IllegalArgumentException(path + " is not a folder");
return Utils.packException(() -> Files.list(folder))
.filter(f -> requireFile ? Files.isRegularFile(f) : Files.isDirectory(f))
.map(Path::toAbsolutePath)
.map(
p ->
Path.of("/")
.resolve(
root.map(r -> p.subpath(Path.of(r).getNameCount(), p.getNameCount()))
.orElse(p))
.toString())
.collect(Collectors.toList());
// We use this method within a try-with-resources statement to ensure that the stream's open
// directory is closed promptly after the stream's operations have completed.
// See
// https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#list(java.nio.file.Path)
try (var directories = Utils.packException(() -> Files.list(folder))) {
return directories
.filter(f -> requireFile ? Files.isRegularFile(f) : Files.isDirectory(f))
.map(Path::toAbsolutePath)
.map(
p ->
Path.of("/")
.resolve(
root.map(r -> p.subpath(Path.of(r).getNameCount(), p.getNameCount()))
.orElse(p))
.toString())
.toList();
}
}

@Override
Expand Down

0 comments on commit 985d4e3

Please sign in to comment.