List java source folders in an eclipse project in the workspace

If you are doing plugin development this is quite easy to do. The ResourceUtils class does the job for you.

			
import org.eclipse.jst.ws.internal.common.ResourceUtils;
...
  IProject project = .....
  IPath srcPath = ResourceUtils.getJavaSourceLocation(project);

Some times there are more than one source folder in the project, If you want to list them all just use,

ResourceUtils.getAllJavaSourceLocations(project)

instead. I had to do it the hardway since I didn’t know how that there was such a function to list java source folders, so I wrote one myself. If anyone wants to do it manually….

public static String[] getJavaProjectSourceDirectories (String projectName) throws CoreException, JavaModelException{
    ArrayList paths = new
    ArrayList();
    IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (project.isOpen() && JavaProject.hasJavaNature(project)){

        IJavaProject javaProject = JavaCore.create(project);


        IClasspathEntry[] classpathEntries = null;

        classpathEntries = javaProject.getResolvedClasspath(true);
        for(inti = 0; i<classpathEntries.length;i++){
            IClasspathEntry entry = classpathEntries[i];

            if(entry.getContentKind() == IPackageFragmentRoot.K_SOURCE){
                IPath path = entry.getPath();

                String srcPath = path.segments()[path.segmentCount()-1];
                paths.add(srcPath);

            }

        }
    }
    return (String[])paths.toArray(new String[0]);

}

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: