javaeclipseapieclipse-plugineclipse-api

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


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?


Solution

  • 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).