Java - traverse through folders and do something if intended folder is present

Viewed 123

Being very new to Java, I'm unable to bring a small concept to a syntactic form. Apologies.

My project structure looks like below & i'm trying to walk thru the sub folders of applications directory & search for a folder named conduit, if present, create a new folder called base parallel to it.

At best I came up with the below code, post that, kind of struggling.

/home/project_A/applications
                |sub_project_A
                  |target
                    |conduit
                |sub_project_B
                  |target
                    |conduit

                |sub_project_C
                  |target
                    |class

                |sub_project_D
                  |target
                    |conduit    

public class Test
{

  public static void main(String[] args)
  {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();
    String appDir = s + "/applications";
    System.out.println("Directory Exists" + appDir);

  }
 }
2 Answers

You can use BFS to traverse the sub directories:

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Queue;

public class MyClass {
public static void main(String[] args) {
    Path currentRelativePath = Paths.get("");
    Queue<Path> paths = new LinkedList<>();
    paths.add(currentRelativePath);
    while(!paths.isEmpty()) {
        Path current = paths.poll();
        File currentFile = current.toFile();
        if(currentFile.isDirectory()) {
            if(currentFile.getName().equals("conduit")) {
                // Found the directory called conduit, Do what you have to do here
            }else {
                for(String fileName : currentFile.list()) {
                    paths.add(Paths.get(currentFile.getAbsolutePath()+"/"+fileName)); 
                }
            }
        }
    }
}
}

Using Files.find is a good way to traverse a series of directories quickly to find files or directories matching any criteria you need. Here is an example which prints off the matches:

BiPredicate<Path, BasicFileAttributes> predicate = (p,a) -> a.isDirectory() && "conduit".equals(p.getFileName().toString());
try(var dirs = Files.find(Path.of("."), Integer.MAX_VALUE, predicate)) {
    dirs.forEach(p -> {
            System.out.println("Found "+p+", create if not exists: "+p.resolveSibling("base"));
        }
    );
}
Related