Grant
Grant

Reputation: 33

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?

Upvotes: 0

Views: 2039

Answers (4)

Stan Towianski
Stan Towianski

Reputation: 409

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.

Upvotes: 0

Bruno Reis
Bruno Reis

Reputation: 37822

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;
  }
});

Upvotes: 4

Jayamohan
Jayamohan

Reputation: 12924

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.

Upvotes: 0

Joe K
Joe K

Reputation: 18424

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
        }
    }
}

Upvotes: 1

Related Questions