'Java FileFilter Doesn't Show Any Output With Filtering .mp3 Extension
I want to filter all mp3 files from a path named "E:\\MUSICS COLLECTION" where are some sub folders under the MUSICS COLLECTION folder.
But, when I run the code it doesn't show any output. I don't know where is the main problem.
The code
import java.io.*;
public class Music2 {
public static void main(String[] args) throws IOException {
File home = new File("E:\\MUSICS COLLECTION");
FileFilter mp3Filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
String fileName = pathname.getName();
if(fileName.endsWith(".mp3")){
return true;
}
return false;
}
};
File[] listRoots = home.listFiles(mp3Filter);
for(File file : listRoots){
System.out.println(file.getPath());
}
}
}
Solution 1:[1]
Since you're expecting the lookup to happen at the subfolders as well, you should walk the file tree
Below code should do that
public static void main(String[] args) {
List<Path> result;
try (Stream<Path> walk = Files.walk(Path.of("E:\\MUSICS COLLECTION"))) {
result = walk.filter(Files::isRegularFile).filter(file -> file.getFileName().toString().endsWith(".mp3"))
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
result.forEach(out::println);
}
P.S: Files.walk(Path.of("E:\\MUSICS COLLECTION")) won't work in java 8 use Files.walk(Paths.get("E:\\MUSICS COLLECTION")) instead
Solution 2:[2]
If you don't want to walk the file tree manually (for whatever reason) as described in @HariHaravelan's answer, Apache Commons IO's FileUtils comes to the rescue:
File home = new File("E:\\MUSICS COLLECTION");
Collection<File> mp3Files = FileUtils.listFiles(home, new String[] {"mp3"}, true);
mp3Files.forEach(System.out::println);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
