简体   繁体   中英

Java loop through files with the same name in a folder with subfolders

I'm writing some Java code to loop through files with the same name in a folder with lots of subfolders, and do some logics on each file:

parentFolder/
            subfolder1/file.txt
            subfolder2/file.txt
            subfolder3/file.txt
            ... ...
            subfolderx/file.txt

above is the structure of what does it look like.

How would I do that?

If you are using Java 7, you could try the visitor pattern implemented in the Path API: Files.walkFileTree(...)

The simplest way to use it is to pass a (an anonymous) subclass of SimpleFileVisitor and do whatever you want whenever you visit a file. For example,

Files.walkFileTree(parentPath, new SimpleFileVisitor() {
  @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
    // you can do whatever you want with "file" here.
    System.out.println("The file is: " + file);
    return FileVisitResult.CONTINUE;
  }
});
String parentFolderPath = "parentFolder";
String fileName = "file.txt";
File parent = new File(parentFolderPath);
for (File subFolder : parent.listFiles()) {
    if (subFolder.isDirectory()) {
        File f = new File(subFolder, fileName);
        if (f.exists()) {
            // your code here
        }
    }
}

Have a look at FileUtils class in Apache Commons.

They have FileUtilsiterateFiles(File directory,IOFileFilter fileFilter,IOFileFilter dirFilter) method where you can specify your file filters.

I would just like to throw out another way to do this. This file search and process software: http://www.softpedia.com/get/File-managers/JFileProcessor.shtml https://github.com/stant/jfileprocessor

Will let you search for files with glob or regex, in subfolders to X or all depth, by name, size, date. You can save to a List window or file. Then you can run a groovy (think java) script to do whatever you want to the list of files; zip or tar them, modify the list strings like sed, delete, move, copy files, grep or ls -l them, whatever. It will also let you massage your list like add to, delete from, subtract one list from another.

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