简体   繁体   中英

How to get all files in a directory with exclusion of subdirectories using regular expression?

Relating to Java code: can any one help me to get all files in a directory with exclusion of sub directories using regular expressions

I have used (. ). to match all files in directory but it also searching subdirectories that I don't want to

You want to use a java.io.FileFilter :

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

...


/**
 * 
 * Search in {@code directory} all files excluding or 
 * including subdirectories matching given {@code regex}.
 * 
 * @param directory The directory where the search is done.
 * @param regex The regex used to match the directories to exclude or include.
 * @param exclude Indicate if the matched directories will be excluded (TRUE) or included (FALSE).
 * 
 * @return All files including or excluding directories matched by {@code regex}. 
 *
 */
public static File[] getAllFiles(String directory, final String regex, final boolean exclude)  {
    File f = new File(directory);

    FileFilter regexFilter = new FileFilter() {
        private Matcher REGEX_FILTER = Pattern.compile(regex).matcher("");

        public boolean accept(File pathname) {
            boolean isDirectory = pathname.isDirectory();

            if (isDirectory && REGEX_FILTER.reset(pathname.getName()).matches()) {
                return !exclude;
            }

            if (isDirectory) {
                return false;
            }

            return true;
        }
    };

    return f.listFiles(regexFilter);
}

Sample usage

// Show all files in current directory with exclusion of subdirectories...
// ... having a name starting with a dot.
for (File file : getAllFiles(".", "^\\..+$")) {
    if (file.isDirectory()) {
        System.out.print("directory:");
    } else {
        System.out.print("     file:");
    }
    System.out.println(file.getCanonicalPath());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM