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
- Create a recursive method
extract(String path). - Create a
Fileobject and calllistFiles()to get an array of all files/folders inside it. - Loop through the array.
- If the item is a Directory, recursively call
extract()on it. - 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
Fileclass 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).