简体   繁体   English

Eclipse API:如何仅使用文件名从IProject获取IFile?

[英]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. 我有一个IProject句柄和一个表示IFile名称的String。

The IFile is a .java class file, and the IProject is a Java project. IFile是一个.java类文件,IProject是一个Java项目。 Ideally, I would like to do this without assuming they are Java files/projects - but the assumption is okay for my purposes. 理想情况下,我想在不假设它们是Java文件/项目的情况下这样做 - 但我的目的是假设是可行的。 Any suggestions? 有什么建议么?

If you want to get the file from IProject recursively, you can use IProject#members. 如果要以递归方式从IProject获取文件,可以使用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). 如果您要查找的文件不能递归调用,您可以使用的IProject#findMembers(字符串)。

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. 如果你要坚持使用资源,你应该使用IResource#accept(IResourceProxyVisitor) - 这是通过资源树最轻量级的方式。 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. 您的访问者将能够向给定的IResourceProxy实例询问项目中每个资源的类型和名称,然后在代理上的匹配项既是文件又具有正确名称时请求完整路径。

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. 如果您愿意通过JDT API,它的SearchEngine就是为这种东西而构建的,它有专门用于查找类型名称的方法。 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. 在实现类中设置一些断点,并尝试从运行时工作台的UI中进行一些Java搜索,以更好地了解它的设置方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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