[英]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 与Java代码有关:谁能帮我使用正则表达式获取目录中的所有文件,但不包括子目录
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
: 您要使用
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);
}
// 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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.