Skip to content

Instantly share code, notes, and snippets.

@PPartisan
Last active April 4, 2023 10:39
Show Gist options
  • Save PPartisan/ae98a9217b89e7f7e54b1b8df8b37bda to your computer and use it in GitHub Desktop.
Save PPartisan/ae98a9217b89e7f7e54b1b8df8b37bda to your computer and use it in GitHub Desktop.
StackOverflow sample for file traversal and a few tests
public final class FileUtils {
//Private constructor
static List<File> fetchSongs(File rootDir){
final File[] files = rootDir.listFiles();
if(isEmpty(files))
return Collections.emptyList();
return fetchSongs(files);
}
private static List<File> fetchSongs(File[] songs) {
ArrayList<File> out = new ArrayList<>();
for(File f: songs)
addSongsIfNotHidden(f, out);
return out;
}
private static void addSongsIfNotHidden(File file, List<File> out) {
if(!isHidden(file))
addIfFileIsDirectoryOrMp3(file, out);
}
private static void addIfFileIsDirectoryOrMp3(File f, List<File> out) {
if(f.isDirectory())
out.addAll(fetchSongs(f));
else if(hasMp3FileType(f))
out.add(f);
}
private static boolean hasMp3FileType(File f) {
return f.getName().endsWith(".mp3");
}
private static boolean isHidden(File f) {
return f.isHidden() || f.getName().startsWith(".");
}
private static boolean isEmpty(Object[] arr) {
return arr == null || arr.length == 0;
}
}
public class FileUtilsTest {
@Rule
public final TemporaryFolder tmp = new TemporaryFolder();
@Test
public void whenDirectoryIsEmpty_thenReturnEmptySongsList() {
Assertions.assertThat(getSongs()).isEmpty();
}
@Test
public void whenDirectoryContainsSingleMp3_thenReturnSongsListForSingleMp3() throws IOException {
final File song = tmp.newFile("song.mp3");
Assertions.assertThat(getSongs()).hasSize(1).containsOnly(song);
}
@Test
public void whenDirectoryContainsSingleMp3_andJpgFile_thenReturnSongsListForSingleMp3Only() throws IOException {
final File song = tmp.newFile("song.mp3");
final File img = tmp.newFile("image.jpg");
Assertions.assertThat(getSongs()).hasSize(1).containsOnly(song).doesNotContain(img);
}
@Test
public void whenDirectoryContainsNestedDirectoriesWithMp3s_thenReturnSongsListForAllNestedMp3s() throws IOException {
tmp.newFolder("spotify");
tmp.newFolder("spotify", "favourites");
final File song1 = tmp.newFile("song1.mp3");
final File song2 = tmp.newFile("spotify/song2.mp3");
final File song3 = tmp.newFile("spotify/favourites/song3.mp3");
Assertions.assertThat(getSongs()).hasSize(3).containsOnly(song1, song2, song3);
}
private List<File> getSongs() {
return fetchSongs(tmp.getRoot());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment