简体   繁体   中英

ArrayList with recursive method

I'm new to using Swing - I have a recursive method which iterates over directories on the hard drive and currently prints out the music tracks - I want to add the tracks to an array list so that I can send the complete list to a JPanel and display it there... How can I stop the array list being cleared when the method is called recursively for each folder? Thanks

I'm not sure that I understand your code, so I'll restart from scratch, by giving you some pseudo-code:

private List<File> getAllAudioFiles(File folder) {
    List<File> result = new ArrayList<>(); 
    // you want a single list. There should be no other list creation in the algorithm.
    addAllAudioFiles(folder, result);
    return result;
}

private void addAllAudioFiles(File folder, List<File> result) {
    for (File file : folder.listFiles()) {
        if (file.isDirectory()) {
            // call this method recursively, to add all the audio files in the subfolder
            // to the SAME list
            addAllAudioFiles(file, result); 
        }
        else if (isAudioFile(file)) {
            result.add(file);
        }
    }
}

Try the following code

public class MusicGetter {

ArrayList<String> tlist = new ArrayList<>();

MusicGetter(String c) {
    addToList(c);
}

private void addToList(String s) {
    File root = new File(s);
    File[] files = root.listFiles();
    for (File f : files) {
        String str = f.getPath();
        if (str.endsWith(".mp3") || str.endsWith(".wav") || str.endsWith(".flac") || str.endsWith(".m4a") || str.endsWith(".ogg") || str.endsWith(".wma")) {
            tlist.add(str);
        }
        if (f.isDirectory()) {
            addToList(f.getPath().toString());
        }
    }
}

public static void main(String[] args) {
    MusicGetter mg = new MusicGetter("E:\\audios");
    for (int i = 0; i < mg.tlist.size(); i++) {
        System.out.println(mg.tlist.get(i));
     }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM