capoocan capoocan - 5 months ago 13
Java Question

How to create packages (folders) in an Eclipse project via plugin

I try to develop a small plugin for Eclipse to create several Java files in several folders (packages) as a starting point for a new module of a larger software.

I've tried to use an

IFile
object like this:

final IFile file = container.getFile(new Path(myFileName));
...
file.create(stream, true, monitor);


That works as long as all folders on the path to the file exists. But it does not create any missing folders (new packages) but throws a "resource not exists" exception.

I could not find any way to do this by
IResource
or
IWorkspace
objects.

Answer

Personally, I use a small method which recursively creates all of the folders, something like:

IFile file = project.getFile(newPath);

prepare((IFolder) file.getParent());

and then the method

public void prepare(IFolder folder) {
    if (!folder.exists()) {
        prepare((IFolder) folder.getParent())
        folder.create(false, false, null);
    }
}

This works well for me.