Anu
Anu

Reputation: 405

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?

Upvotes: 3

Views: 1000

Answers (2)

sil
sil

Reputation: 450

I came across this problem yesterday. Unfortunately I can no longer find the link where I got the information I needed to fix the problem, but here is the solution

The project root "ProjectName" is already in the classpath and therefore no subfolder of it can be added to the classpath. To include "ProjectName/src" in the classpath, I simply replace the "ProjectName" classpath entry with the new "ProjectName/src" entry.

Upvotes: 0

nitind
nitind

Reputation: 20003

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.

Upvotes: 1

Related Questions