Question

A few weeks ago I used this thread Grabbing specific files in a folder to grab a list of mkv files from a directory provided by a third party. However, the structure of the directory has now changed, so I need to recursively cycle through all of the folders to find the .mkv files.

I have heard that the Apache commons library has the FileUtils.listFiles() method, which seems promising. As far as I know that returns a collection by default though, and collections do not guarantee that order is preserved (since these are .mkv video files, order is very important). Do any of you have experience with this sort of thing?

Was it helpful?

Solution

How many levels deep is your directory structure?

For example, say previously your files were inside a root directory, and now they're inside root/domain1, root/domain2, root/domain3, etc.

For that, I wrote something rather simple.

    String rootPath = <path_to_root>;
    File[] domains = new File(rootPath).listFiles();
    for (File domain : domains) {
        if (domain.isDirectory()) {
            File[] files = new File(domain.getAbsolutePath()).listFiles();
            for (File file : files) {
                if (file.isFile() && file.getAbsolutePath().endsWith(".mkv")) {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }

OTHER TIPS

starting with java 7 there's really no need to use any 3rd party library for traversing file trees. have a look at the new Path API. specifically FileVisitor. you could easily write one that lists out only files who's name ends in ".mkv"

Using FileUtils.listFiles(), if directory has a lots of files inside, can run into NPE or poor performance.

If you need to order file by using file's metadata and not only by filename you can use one between

and do something like

  • Create a class with necessary file properties used for order (class FileMetadata) which implements Comparable
  • Create an emtpy List<FileMetadata>
  • Traverse directory and add to your List<>
  • Call Collections.sort(List<>); (this call use FileMetadata's Comparable implementation)

Another way, if you need total ordering along directories a good solution can be use a [ordered TreeMap](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top