Reputation: 15814
Given only the name of a .java file (a String) and access to its IJavaProject
, how can I find the file's IFile or fully qualified path? For example, if the file name is Foo.java
, I have the String Foo
.
Here is my attempt, but it is too slow:
// Find the fully qualified path from "fileName".
for (ICompilationUnit unit : JDTUtility.getCompilationUnits(javaProject))
{
if (unit.getElementName().equals(fileName))
file = (IFile) unit.getResource();
}
// Get a list of ICompilationUnits from an IJavaProject object
public static List<ICompilationUnit> getCompilationUnits(IJavaProject javaProject)
{
ArrayList<ICompilationUnit> units = new ArrayList<>();
try
{
IPackageFragmentRoot[] packageFragmentRoots = javaProject.getAllPackageFragmentRoots();
for (int i = 0; i < packageFragmentRoots.length; i++)
{
IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
IJavaElement[] fragments = packageFragmentRoot.getChildren();
for (int j = 0; j < fragments.length; j++)
{
IPackageFragment fragment = (IPackageFragment) fragments[j];
IJavaElement[] javaElements = fragment.getChildren();
for (int k = 0; k < javaElements.length; k++)
{
IJavaElement javaElement = javaElements[k];
if (javaElement.getElementType() == IJavaElement.COMPILATION_UNIT)
{
units.add((ICompilationUnit) javaElement);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return units;
}
Upvotes: 0
Views: 433
Reputation: 111142
You can get the IProject
from the IJavaProject
using the getProject()
method:
IProject project = javaProject.getProject();
The fastest way to scan the project is the accept(IResourceProxyVisitor)
method:
project.accept(new IResourceProxyVisitor()
{
@Override
public boolean visit(IResourceProxy proxy) throws CoreException
{
if ("Foo.java").equals(proxy.getName))
{
IPath workspacePath = proxy.requestFullPath();
// TODO deal with path
// Alternative
IResource resource = proxy.requestResource();
}
}
});
Upvotes: 2