Try below solution :
Note : Before apply any git changes make sure you have backup for necessary files.
Use the git object to create a TreeWalk that will allow you to traverse the repository's tree and find the subdirectory you're interested in. Specify the starting path as the root of the repository:
try (Git git = Git.open(LOCAL_REPOSITORY_PATH.toFile())) {
Repository repository = git.getRepository();
// Get the tree for the repository's HEAD commit
RevWalk revWalk = new RevWalk(repository);
RevCommit commit = revWalk.parseCommit(repository.resolve(Constants.HEAD));
RevTree tree = commit.getTree();
// Create a TreeWalk starting from the root of the repository
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
// Specify the path of the subdirectory you want to check out
treeWalk.setFilter(PathFilter.create("foo/bar"));
if (!treeWalk.next()) {
throw new IllegalStateException("Subdirectory not found");
}
// Get the ObjectId of the subdirectory's tree
ObjectId subdirectoryTreeId = treeWalk.getObjectId(0);
treeWalk.close();
// Create a new Git object with the shallow, bare repository
Git subGit = new Git(repository);
// Checkout the subdirectory's tree to a temporary directory
Path temporaryDirectory = Files.createTempDirectory("subdirectory");
subGit.checkout().setStartPoint(subdirectoryTreeId.getName()).setAllPaths(true).setForce(true).setTargetPath(temporaryDirectory.toFile()).call();
// Now you can use the Java file system API to process the files in the temporary directory
// Clean up the temporary directory when you're done
FileUtils.deleteDirectory(temporaryDirectory.toFile());
}
In the code above, we use a TreeWalk to traverse the repository's tree and find the subdirectory you specified (foo/bar). We then get the ObjectId of the subdirectory's tree and create a new Git object with the repository. Finally, we use checkout() to check out the subdirectory's tree to a temporary directory, and you can use the Java file system API to process the files in that directory. Don't forget to clean up the temporary directory when you're done.
Note that the code assumes you have the necessary JGit and Java IO imports in place.