2

In my Generator.xtend class I'm trying to create a package from a given path, like given "com/example/config", I want to create the config folder in the example folder within the com folder. This is what I've tried so far:

def static generateJavaPackages(String pkgName, IProject projectDir, IProgressMonitor monitor) {
        val mainJavaFolder = '/src/main/java/'

        /* create package folders */
        try {

            projectDir.getFolder(mainJavaFolder + pkgName).create(true, true, monitor)
            
        } catch (ResourceException exception) {

            exception.printStackTrace()
        }
    }

Is there a method similar to mkdir that creates the non-existent folders in the path?

Mukendi
  • 43
  • 6

2 Answers2

1

You have to create all the intermediate folders yourself.

This is how Eclipse JDT does that:

public static void createFolder(IFolder folder, boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
    if (!folder.exists()) {
        IContainer parent = folder.getParent();
        if (parent instanceof IFolder) {
            createFolder((IFolder)parent, force, local, null);
        }
        folder.create(force, local, monitor);
    }
}

Which is just going up through the parents of the folder checking they exist and creating them if not.

greg-449
  • 109,219
  • 232
  • 102
  • 145
0

I stumbled upon a shorter solution - and I might say a better one - while studying the API:

val mainJavaFolderPath = new Path("/src/main/java")
    // Segmenting with .segments was the clue for me
    for (segment : mainJavaFolderPath.segments) {
        var pkgFolder = rootDir.getFolder(new Path(segment))
        if (!pkgFolder.exists())
            pkgFolder.create(true, true, monitor)
    }
Mukendi
  • 43
  • 6
  • This looks like it creates each segment in the root directory – greg-449 Aug 22 '21 at 09:55
  • @greg-449 it creates the src folder inside the project dir, then the main folder inside src and finally the java folder inside the main folder. Not all segments as siblings inside the root dir. – Mukendi Sep 01 '21 at 22:27
  • It calls rootDir.getFolder for each segment, which returns a folder in the root directory. The segments are just "src", "main", "java" - how does that nest the folders? – greg-449 Sep 02 '21 at 07:07