Java Directory to File List getAllFilesInFolder(File rootFolder, FileFilter filter, int maxFilesRequired)

Here you can find the source of getAllFilesInFolder(File rootFolder, FileFilter filter, int maxFilesRequired)

Description

Retrieves a List with at most maxFiles files that are in a folder or any of the subfolders in that folder satisfying a condition.

License

Open Source License

Parameter

Parameter Description
rootFolder The folder from within to find the files
filter The FileFilter condition
maxFilesRequired Maximum number of files in the List. 0 indicates no maximum

Exception

Parameter Description
IllegalArgumentException Thrown if <tt>maxFilesRequired</tt> argument is less than zero

Return

The list containing all the files

Declaration

public static List<File> getAllFilesInFolder(File rootFolder, FileFilter filter, int maxFilesRequired) 

Method Source Code

//package com.java2s;
/*/*w  ww . j a va  2  s. c o m*/
 * This file is part of Musicott software.
 *
 * Musicott software is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Musicott library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Musicott. If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (C) 2015, 2016 Octavio Calleya
 */

import java.io.*;

import java.util.*;

public class Main {
    /**
     * Retrieves a {@link List} with at most <tt>maxFiles</tt> files that are in a folder or
     * any of the subfolders in that folder satisfying a condition.
     * If <tt>maxFilesRequired</tt> is 0 all the files will be retrieved.
     *
     * @param rootFolder       The folder from within to find the files
     * @param filter           The {@link FileFilter} condition
     * @param maxFilesRequired Maximum number of files in the List. 0 indicates no maximum
     *
     * @return The list containing all the files
     *
     * @throws IllegalArgumentException Thrown if <tt>maxFilesRequired</tt> argument is less than zero
     */
    public static List<File> getAllFilesInFolder(File rootFolder, FileFilter filter, int maxFilesRequired) {
        List<File> finalFiles = new ArrayList<>();
        if (!Thread.currentThread().isInterrupted()) {
            if (maxFilesRequired < 0)
                throw new IllegalArgumentException("maxFilesRequired argument less than zero");
            if (rootFolder == null || filter == null)
                throw new IllegalArgumentException("folder or filter null");
            if (!rootFolder.exists() || !rootFolder.isDirectory())
                throw new IllegalArgumentException("rootFolder argument is not a directory");

            int remainingFiles = addFilesDependingMax(finalFiles, rootFolder.listFiles(filter), maxFilesRequired);

            if (maxFilesRequired == 0 || remainingFiles > 0) {
                File[] rootSubFolders = rootFolder.listFiles(File::isDirectory);
                addFilesFromFolders(finalFiles, rootSubFolders, maxFilesRequired, remainingFiles, filter);
            }
        }
        return finalFiles;
    }

    /**
     * Add files to a {@link List} depending a {@code maxFilesRequired} parameter.
     * <ul>
     *     <li>
     *         If it's 0, all files are added.
     *     </li>
      *     <li>
      *         If it's greater than the actual number of files, all files are added too.
      *     </li>
     *     <li>
     *         If it's less than the actual number of files, the required number
     *         of files are added
     *     </li>
     * </ul>
     *
     * @param files            The collection of final files
     * @param subFiles         An Array of files to add to the collection
     * @param maxFilesRequired The maximum number of files to add to the collection
     *
     * @return The remaining number of files to be added
     */
    private static int addFilesDependingMax(List files, File[] subFiles, int maxFilesRequired) {
        int remainingFiles = maxFilesRequired;
        if (maxFilesRequired == 0) // No max = add all files
            files.addAll(Arrays.asList(subFiles));
        else if (maxFilesRequired < subFiles.length) { // There are more valid files than the required
            files.addAll(Arrays.asList(Arrays.copyOfRange(subFiles, 0, maxFilesRequired)));
            remainingFiles -= files.size(); // Zero files remaining in the folder
        } else if (subFiles.length > 0) {
            files.addAll(Arrays.asList(subFiles)); // Add all valid files
            remainingFiles -= files.size();
        }
        return remainingFiles;
    }

    /**
     * Adds files to a {@link List} from several folders depending of a maximum required files,
     * the remaining files to be added, using a {@link FileFilter}.
     *
     * @param files          The collection of final files
     * @param folders          The folders where the files are
     * @param maxFilesRequired The maximum number of files to add to the collection
     * @param remainingFiles   The remaining number of files to add
     * @param filter          The {@link FileFilter} to use to filter the files in the folders
     */
    private static void addFilesFromFolders(List files, File[] folders, int maxFilesRequired, int remainingFiles,
            FileFilter filter) {
        int subFoldersCount = 0;
        int remaining = remainingFiles;
        while ((subFoldersCount < folders.length) && !Thread.currentThread().isInterrupted()) {
            File subFolder = folders[subFoldersCount++];
            List<File> subFolderFiles = getAllFilesInFolder(subFolder, filter, remaining);
            files.addAll(subFolderFiles);
            if (remaining > 0)
                remaining = maxFilesRequired - files.size();
            if (maxFilesRequired > 0 && remaining == 0)
                break;
        }
    }
}

Related

  1. getAllFilesInDirectory(File directory, List files)
  2. getAllFilesInDirectory(String directoryPath)
  3. getAllFilesInDirectory(String dirName)
  4. getAllFilesInDirectory(String path)
  5. getAllFilesInDirMatchingPattern(String directory, final String regex, final boolean first_match2)
  6. getAllFilesInFolder(String folder)
  7. getAllFilesInFolderAndSubFolders(String folder)
  8. getAllFilesInHierarchy(final String basePath, final FilenameFilter filter)
  9. getAllFilesInSubFolder(String base, String ending)