Eclipse Plugin - How do I create all folders (IFolders) in a given path (IPath)

Viewed 97

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?

2 Answers

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.

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