I am trying to programmatically access the src/ directory in an Eclipse project (type IProject).
Basically, my problem is as follows:
- INP开发者_开发问答UT: IProject
- OUTPUT: Return the src directory in this IProject
- Notes: The src directory may be called anything else (it need not be "src" every time -- it is decided when creating the java project)
Any pointers on how I can do this?
- Cast the
IProject
toIJavaProject
. - Get the array of
IPackageFragmentRoot
usinggetAllPackageFragmentRoots()
- Get the one(s) which have
getKind() == IPackageFragmentRoot.K_SOURCE
The last answer did not work for me for the point number one, but following did:
IProject project = ...
if (project.isOpen() && JavaProject.hasJavaNature(project))
{
IJavaProject javaProject = JavaCore.create(project);
...
}
I had the same issue, here is code:
if (project == null) return null;
List<IJavaElement> ret = new ArrayList<IJavaElement>();
IJavaProject javaProject = JavaCore.create(project);
try {
IPackageFragmentRoot[] packageFragmentRoot = javaProject.getAllPackageFragmentRoots();
for (int i = 0; i < packageFragmentRoot.length; i++){
if (packageFragmentRoot[i].getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && !packageFragmentRoot[i].isArchive())
ret.add(packageFragmentRoot[i]);
}
} catch (JavaModelException e) {
e.printStackTrace();
return null;
}
return ret;
精彩评论