简体   繁体   中英

Eclipse API: Get IFile or fully-qualified name from IJavaProject using only the file's name string

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;
}

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();
        }
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM