简体   繁体   中英

Java open files with given extension in a directory hierarchy

I implemented a recursive method to traverse a directory hierarchy looking for files with a given extension; however I'm not convinced this is the easiest way and it involves isDirectory() , listFiles() , etc.

Is there a way to do that without explicitly writing a recursive method: I'm thinking something like find that would directly return a list of files or filenames (with their full path) at any level in the structure matching the correct extension. I would then just loop over these files.

Any help appreciated.

您也可以使用Apache Commons FileUtis

FileUtils.listFiles(dir, extensions, true);

Use java.io.File#listFiles() ;

public File[] finder( String dirName){
    File dir = new File(dirName);
    return dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String filename){
            return filename.endsWith(".txt"); 
        }
    });
}

Edit: If you would like to discover the directory in recursive take a look at

FileUtilslistFiles(File directory, String[] extensions, boolean recursive)

with a filter.

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