views:

48

answers:

2

My main goal:

if the user selects a directory it scans the whole folder for mp3 files and returns them. If he selects some mp3 files it returns them.

To return the selected files was an easy one but to scan the directory for mp3's isn't as easy as I first thought. And I think to do that I first new to decide if the user selected a file or directory, but how? Since I can get both with getSelectedFiles().

+1  A: 

You can use File.isDirectory() and File.isFile() to determine if a File is a directory or a normal file, respectively.

ColinD
A: 

Since you want your users to select just a directory, you will need to find the mp3 files yourself.

You can recursively traverse a directory looking for files that end in ".mp3".

public static void findMp3s(File root, List<File> toBuildUp) {
    // if the File is not a directory, and the name ends with mp3
    // we will add it to our list of mp3s
    if (!root.isDirectory() && root.getName().endsWith("mp3")) {
        toBuildUp.add(root);
        return;
    }
    if (!file.isDirectory())
        return;
    // Now, we know that root is a Directory
    // We will look through every file and directory under root,
    // and recursively look for more mp3 files
    for (File f: root.listFiles()){
        findMp3s(f, toBuildUp);
    }
}

The preceding method will recursively traverse all directories and populate toBuildUp with every mp3 file under that directory.

You will call this method like:

List<File> allMp3s = new ArrayList<File>();
findAllMp3s(selectedDirectory, allMp3s);
jjnguy
If the file is not a directory and does not end with "mp3" then your for loop will throw a null pointer exception.
rancidfishbreath
@rancid Thanks for pointing out a flaw in my logic.
jjnguy