Java FileFilter Doesn't Show Any Output With Filtering .mp3 Extension

177 Views Asked by At

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());
   }
  }
}
2

There are 2 best solutions below

6
HariHaravelan On BEST ANSWER

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

5
dpr On

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);