Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to list all mp3 file in specified folder.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to list all mp3 file in specified folder.

Objective

Write a Java program to recursively list all .mp3 files in a specified folder and its subfolders.

Algorithm / Approach

  1. Create a recursive method extract(String path).
  2. Create a File object and call listFiles() to get an array of all files/folders inside it.
  3. Loop through the array.
  4. If the item is a Directory, recursively call extract() on it.
  5. If it is a File, check if its name ends with .mp3. If so, print its path.
MusicList.java
import java.io.*;
class MusicList {
 public static void main(String args[]){
 extract("e:\\music\\");
 }
 static void extract(String p){ 
  File f=new File(p);
  File l[]=f.listFiles();
  for(File x:l) {
    if(x.isDirectory()){
        extract(x.getPath());
    }
    else{
      String n = x.getName();
      if(n.endsWith(".mp3")){
       String p = x.getPath();
       String fn = x.getName();
       System.out.println(p+"\\"+fn);
      }
    }
  }
 }
}

Expected Output

//list all mp3 file available in
//E:\Music folder

Explanation of the Program

  • The File class in Java represents file and directory pathnames.
  • Directories can contain other directories, which contain other directories. To search an entire drive, you must use Recursion—a programming technique where a method calls itself to drill down into nested structures until it hits the bottom.

Complexity

Time Complexity O(n) - Where n is the total number of files/folders in the tree.
Space Complexity O(d) - Where d is the maximum depth of the folder tree (due to call stack overhead).
ADVERTISEMENT