简体   繁体   中英

Regex for files in a directory

是否可以使用正则表达式来获取目录中与给定模式匹配的文件的文件名,而无需手动遍历所有文件。

You could use File.listFiles(FileFilter) :

public static File[] listFilesMatching(File root, String regex) {
    if(!root.isDirectory()) {
        throw new IllegalArgumentException(root+" is no directory.");
    }
    final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
    return root.listFiles(new FileFilter(){
        @Override
        public boolean accept(File file) {
            return p.matcher(file.getName()).matches();
        }
    });
}

EDIT

So, to match files that look like: TXT-20100505-XXXX.trx where XXXX can be any four successive digits, do something like this:

listFilesMatching(new File("/some/path"), "XT-20100505-\\d{4}\\.trx")

EDIT

Starting with Java8 the complete 'return'-part can be written with a lamda-statement:

    return root.listFiles((File file) -> p.matcher(file.getName()).matches());  

implement FileFilter (just requires that you override the method

public boolean accept(File f)

then, every time that you'll request the list of files, jvm will compare each file against your method. Regex cannot and shouldn't be used as java is a cross platform language and that would cause implications on different systems.

package regularexpression;

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

public class RegularFile {
    public static void main(String[] args) {
        new RegularFile();
    }

    public RegularFile() {

        String fileName = null;
        boolean bName = false;
        int iCount = 0;
        File dir = new File("C:/regularfolder");
        File[] files = dir.listFiles();
        System.out.println("List Of Files ::");

        for (File f : files) {

            fileName = f.getName();
            System.out.println(fileName);

            Pattern uName = Pattern.compile(".*l.zip.*");
            Matcher mUname = uName.matcher(fileName);
            bName = mUname.matches();
            if (bName) {
                iCount++;

            }
        }
        System.out.println("File Count In Folder ::" + iCount);

    }
}

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