Search code examples
javafilefilter

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

  • 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