Java Recursive List recursiveListFile(File folder)

Here you can find the source of recursiveListFile(File folder)

Description

recursive List File

License

Apache License

Declaration

public static List<String> recursiveListFile(File folder) 

Method Source Code

//package com.java2s;
/*//ww  w .  java2  s .  c o m
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

import java.io.File;

import java.util.ArrayList;

import java.util.List;

import java.util.function.Predicate;

public class Main {
    public static List<String> recursiveListFile(File folder) {
        return recursiveListFile(folder, "", f -> true);
    }

    public static List<String> recursiveListFile(File folder, String prefix, Predicate<File> filter) {
        List<String> files = new ArrayList<String>();
        for (File child : safeListFiles(folder)) {
            filesInFolder(files, child, prefix, filter);
        }
        return files;
    }

    /**
     * Returns {@link File#listFiles()} on a given file, avoids returning null when an IO error occurs.
     *
     * @param file directory whose files will be returned
     * @return {@link File#listFiles()}
     * @throws IllegalArgumentException when the file is a directory or cannot be accessed
     */
    private static File[] safeListFiles(final File file) {
        final File[] children = file.listFiles();
        if (children != null) {
            return children;
        } else {
            throw new IllegalArgumentException(
                    String.format("Unable to retrieve contents of directory '%s'.", file.getAbsolutePath()));
        }
    }

    private static void filesInFolder(List<String> files, File file, String relativePath, Predicate<File> filter) {
        if (file.isDirectory()) {
            relativePath += file.getName() + "/";
            for (File child : safeListFiles(file)) {
                filesInFolder(files, child, relativePath, filter);
            }
        } else {
            if (filter.test(file)) {
                files.add(relativePath + file.getName());
            }
        }
    }
}

Related

  1. recursiveList(File dir, FilenameFilter filter)
  2. recursiveListFiles(File baseDir, final FileFilter filter)
  3. recursiveListFiles(File dir, FileFilter filter)
  4. recursiveListFiles(File file, List files)
  5. recursiveListFiles(String path)