Eclipse API: How to get IFile from an IProject using only the file name?

1.2k views Asked by At

As stated in the title, I do not have the package names or information. I have a handle to the IProject and a String representing the name of the IFile.

The IFile is a .java class file, and the IProject is a Java project. Ideally, I would like to do this without assuming they are Java files/projects - but the assumption is okay for my purposes. Any suggestions?

2

There are 2 answers

0
Kohei Mikami On BEST ANSWER

If you want to get the file from IProject recursively, you can use IProject#members.

Example)

public IFile findFileRecursively(IContainer container, String name) throws CoreException {
    for (IResource r : container.members()) {
        if (r instanceof IContainer) {
            IFile file = findFileRecursively((IContainer) r, name);
            if(file != null) {
                return file;
            }
        } else if (r instanceof IFile && r.getName().equals(name)) {
            return (IFile) r;
        }
    }

    return null;
}

You can call the method as follows.

IFile file = findFileRecursively(project, "Foo.java");

If you want to find the file not recursively, you can use IProject#findMembers(String).

0
nitind On

You should use IResource#accept(IResourceProxyVisitor) if you're going to stick to resources--it's the most lightweight way to go through the resources tree. Your visitor will be able to ask the given IResourceProxy instance for each resource in the project its type and name, and then request the full path when it has a match on the proxy being both a file and having the right name.

If you are willing to go through the JDT APIs, its SearchEngine is built for this kind of thing, and it has methods for finding on type names specifically. Set some breakpoints in the implementation class and try doing some Java Searches from the UI of a runtime workbench to get a better feel for how it's set up.