From 078169109d789fd0a96cc5401485117f60f120bb Mon Sep 17 00:00:00 2001 From: kwoyke Date: Wed, 30 Dec 2020 12:39:45 +0100 Subject: [PATCH] BAEL-4755: Add Files.list example (#10356) --- .../main/java/com/baeldung/listfiles/ListFiles.java | 13 ++++++++++++- .../com/baeldung/listfiles/ListFilesUnitTest.java | 7 ++++++- 2 files changed, 18 insertions(+), 2 deletions(-) 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));