Java File Find find(File baseFile, String regex)

Here you can find the source of find(File baseFile, String regex)

Description

Find the file whose name matches the given regular expression.

License

Open Source License

Declaration

public static File find(File baseFile, String regex) 

Method Source Code


//package com.java2s;
import java.io.File;

import java.io.FilenameFilter;

public class Main {
    /**/* ww w. ja v  a 2 s  .c  o m*/
     * Find the file whose name matches the given regular
     * expression. The regex is matched against the absolute
     * path of the file.
     * 
     * This could probably use a lot of optimization!
     */
    public static File find(File baseFile, String regex) {
        if (baseFile.getAbsolutePath().matches(regex)) {
            return baseFile;
        }
        if (baseFile.exists() && baseFile.isDirectory()) {
            for (File child : listFiles(baseFile)) {
                File foundFile = find(child, regex);
                if (foundFile != null) {
                    return foundFile;
                }
            }
        }
        return null;
    }

    /**
     * Basically just like {@link File#listFiles()} but instead of returning null
     * returns an empty array. This fixes bug 43729
     */
    public static File[] listFiles(File dir) {
        File[] result = dir.listFiles();
        if (result == null) {
            result = new File[0];
        }
        return result;
    }

    /**
     * Basically just like {@link File#listFiles(FilenameFilter)} but instead of returning null
     * returns an empty array. This fixes bug 43729
     */
    public static File[] listFiles(File dir, FilenameFilter filter) {
        File[] result = dir.listFiles(filter);
        if (result == null) {
            result = new File[0];
        }
        return result;
    }
}

Related

  1. find(File absolutePath, FileFilter filter)
  2. find(File dir, String baseName)
  3. find(File dir, String suffix, Set ignore)
  4. find(File file)
  5. find(File file, Pattern pattern, int limit, List found, Set visited)