Android Directory Search findFiles(File dir, FileFilter filter)

Here you can find the source of findFiles(File dir, FileFilter filter)

Description

Finds all files (non-recursively) in a directory based on the FileFilter.

License

Apache License

Declaration

public static File[] findFiles(File dir, FileFilter filter)
        throws FileNotFoundException 

Method Source Code

//package com.java2s;
/*/*from  w  w  w.j  a  v  a2  s .  c  o m*/
 * #%L
 * ch-commons-util
 * %%
 * Copyright (C) 2012 Cloudhopper by Twitter
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      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.
 * #L%
 */

import java.io.File;
import java.io.FileFilter;

import java.io.FileNotFoundException;

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    /**
     * Finds all files (non-recursively) in a directory based on the FileFilter.
     * This method is slightly different than the JDK File.listFiles() version
     * since it throws an error if the directory does not exist or is not a
     * directory.  Also, this method only finds files and will skip including
     * directories.
     */
    public static File[] findFiles(File dir, FileFilter filter)
            throws FileNotFoundException {
        if (!dir.exists()) {
            throw new FileNotFoundException("Directory " + dir
                    + " does not exist.");
        }

        if (!dir.isDirectory()) {
            throw new FileNotFoundException("File " + dir
                    + " is not a directory.");
        }

        // being matching process, create array for returning results
        ArrayList<File> files = new ArrayList<File>();

        // get all files in this directory
        File[] allFiles = dir.listFiles();

        // were any files returned?
        if (allFiles != null && allFiles.length > 0) {
            // loop thru every file in the dir
            for (File f : allFiles) {
                // only match files, not a directory
                if (f.isFile()) {
                    // delegate matching to provided file matcher
                    if (filter.accept(f)) {
                        files.add(f);
                    }
                }
            }
        }

        // based on filesystem, order of files not guaranteed -- sort now
        File[] r = files.toArray(new File[0]);
        Arrays.sort(r);
        return r;
    }
}

Related

  1. find(File pDirectory, String pRegex)
  2. recursiveSearch(java.io.File dir, String fileName)