Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 747
capoocan Avatar asked Dec 22 '11 16:12

capoocan


People also ask

How do you create a package in Eclipse?

You can add a new package in Eclipse by right-clicking on your project and selecting New > Package. Note that a package doesn't really exist until you create some class or interface in that package. The more logical way to do this is to simply define a package when creating a new class.

How do I create a folder in Eclipse project?

You can link to a folder by using the Advanced option on the New->Folder dialog or drag/drop the folder from a file system navigator (Explorer,Nautilus, etc) onto your project in Eclipse. You will get an option to copy the folder or link to it in the file system.

Can we create a folder inside a package in Eclipse?

I would suggest to add a resources folder at the top of your app tree so that your data and your classes are separated. But if you want to just add subpackage, do not create a new folder, just create a new package such as app. models. Folder1.


1 Answers

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.

like image 177
Matthew Farwell Avatar answered Sep 19 '22 04:09

Matthew Farwell