Skip to content

Commit 91f411e

Browse files
committed
Add list files recursively snippet
1 parent e3d03e0 commit 91f411e

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Update the sample application with the snippet and add a test for it. After prov
1616
### File
1717
* [List directories](#list-directories)
1818
* [List files in directory](#list-files-in-directory)
19+
* [List files in directory recursively](#list-files-in-directory-recursively)
1920
* [Read lines from file to string list](#read-lines-from-file-to-string-list)
2021

2122
### Math
@@ -86,6 +87,27 @@ Update the sample application with the snippet and add a test for it. After prov
8687

8788
[⬆ back to top](#table-of-contents)
8889

90+
### List files in directory recursively
91+
92+
```java
93+
public static List<File> listAllFiles(String path) {
94+
List<File> all = new ArrayList<>();
95+
File[] list = new File(path).listFiles();
96+
if (list != null) { // In case of access error, list is null
97+
for (File f : list) {
98+
if (f.isDirectory()) {
99+
all.addAll(listAllFiles(f.getAbsolutePath()));
100+
} else {
101+
all.add(f.getAbsoluteFile());
102+
}
103+
}
104+
}
105+
return all;
106+
}
107+
```
108+
109+
[⬆ back to top](#table-of-contents)
110+
89111
### Read lines from file to string list
90112

91113
```java

src/main/java/Library.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,4 +159,24 @@ public static boolean isPalindrome(String s) {
159159
public static File[] listFilesInDirectory(final File folder) {
160160
return folder.listFiles(File::isFile);
161161
}
162+
163+
/**
164+
* Recursively list all the files in directory
165+
* @param path the path to start the search from
166+
* @return list of all files
167+
*/
168+
public static List<File> listAllFiles(String path) {
169+
List<File> all = new ArrayList<>();
170+
File[] list = new File(path).listFiles();
171+
if (list != null) { // In case of access error, list is null
172+
for (File f : list) {
173+
if (f.isDirectory()) {
174+
all.addAll(listAllFiles(f.getAbsolutePath()));
175+
} else {
176+
all.add(f.getAbsoluteFile());
177+
}
178+
}
179+
}
180+
return all;
181+
}
162182
}

src/test/java/LibraryTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,13 @@ public void testListFilesInDirectory() {
172172
assertEquals(1, files.length);
173173
assertEquals("src/test/resources/somelines.txt", files[0].toString());
174174
}
175+
176+
/**
177+
* Tests for {@link Library#listAllFiles(String)}
178+
*/
179+
@Test
180+
public void testListAllFiles() {
181+
List<File> files = Library.listAllFiles("src/test/resources");
182+
assertEquals(3, files.size());
183+
}
175184
}

0 commit comments

Comments
 (0)