diff --git a/core-java-modules/core-java-io-2/src/main/java/com/baeldung/listfiles/ListFiles.java b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/listfiles/ListFiles.java index 2275128dfe..c108d9ed96 100644 --- a/core-java-modules/core-java-io-2/src/main/java/com/baeldung/listfiles/ListFiles.java +++ b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/listfiles/ListFiles.java @@ -24,9 +24,20 @@ public class ListFiles { .collect(Collectors.toSet()); } + public Set listFilesUsingFilesList(String dir) throws IOException { + try (Stream stream = Files.list(Paths.get(dir))) { + return stream + .filter(file -> !Files.isDirectory(file)) + .map(Path::getFileName) + .map(Path::toString) + .collect(Collectors.toSet()); + } + } + public Set listFilesUsingFileWalk(String dir, int depth) throws IOException { try (Stream stream = Files.walk(Paths.get(dir), depth)) { - return stream.filter(file -> !Files.isDirectory(file)) + return stream + .filter(file -> !Files.isDirectory(file)) .map(Path::getFileName) .map(Path::toString) .collect(Collectors.toSet()); diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/listfiles/ListFilesUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/listfiles/ListFilesUnitTest.java index a87097f085..5b4efc9e58 100644 --- a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/listfiles/ListFilesUnitTest.java +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/listfiles/ListFilesUnitTest.java @@ -25,10 +25,15 @@ public class ListFilesUnitTest { }; @Test - public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException { + public void givenDir_whenUsingJAVAIO_thenListAllFiles() { assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY)); } + @Test + public void givenDir_whenUsingFilesList_thenListAllFiles() throws IOException { + assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFilesList(DIRECTORY)); + } + @Test public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException { assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));