Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Source Folder Programmatically

I have tried to create one source folder in a java project with the below code.

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(projectName);
    project.create(null);
    project.open(null);
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    project.setDescription(description, null);
    IJavaProject javaProject = JavaCore.create(project); 
    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
    javaProject.setRawClasspath(newEntries, null);

But it is giving Java Model Exception from the last line : javaProject.setRawClasspath(newEntries, null);

Java Model Exception: Java Model Status [Cannot nest 'ProjectName/src' inside 'ProjectName'. To enable the nesting exclude 'src/' from 'ProjectName']
    at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:784)
    at org.eclipse.jdt.internal.core.JavaProject.setRawClasspath(JavaProject.java:3102)
    at org.eclipse.jdt.internal.core.JavaProject.setRawClasspath(JavaProject.java:3064)
    at org.eclipse.jdt.internal.core.JavaProject.setRawClasspath(JavaProject.java:3117)

Can any one tell me how can I create source folder programmatically?

like image 205
Anu Avatar asked Jul 11 '26 20:07

Anu


1 Answers

When you called javaProject.getPackageFragmentRoot(), you created a build path for the project using itself as the source folder. Skip it, you can just get the project-relative path from your IFolder instance and make your newSourceEntry from that.

like image 60
nitind Avatar answered Jul 13 '26 10:07

nitind