简体   繁体   English

在IProject中搜索文件 - Eclipse

[英]Search file in IProject - Eclipse

I need to find a specific file present in eclipse project which is in classpath of project. 我需要找到eclipse项目中存在的特定文件,该文件位于项目的类路径中。

I have IProject instance but Dont know how to get IFile instance 我有IProject实例但不知道如何获得IFile实例

The IProject interface extends the IContainer which has several findMember methods. IProject接口扩展了IContainer ,它有几个findMember方法。 You get an IResource which can be casted down to IFile after checking its' type using getType . 你得到一个IResource,可以在使用getType检查其类型后将其转换为IFile Go over those interfaces, they are properly documented. 浏览这些界面,它们都有适当的文档记录。

I was facing the same problem and this is in short what i did: 我遇到了同样的问题,这就是我所做的:

IResource getResource(IProject project, String folderPath, String fileName) {

    IJavaProject javaProject = JavaCore.create(project);
    for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
        IPackageFragment folderFragment = root.getPackageFragement(folderPath);
        IResource folder = folderFragment.getResource();
        if (folder == null || ! folder.exists() || !(folder instanceof IContainer)) {
            continue;
        }

        IResource resource = ((IContainer) folder).findMember(fileName);
        if (resource.exists()) {
            return resource;
        }
    }

    // file not found in any source path
    return null;
}

It looks pretty ugly and maybe there's a more direct approach. 它看起来很丑陋,也许有更直接的方法。 But it works. 但它的确有效。

If you need to use the classpath, you have to use IJavaProject and the way fragments work prevents directly searching for the file path, because it will assume the "." 如果需要使用类路径,则必须使用IJavaProject并且片段的工作方式可以防止直接搜索文件路径,因为它将采用“。” (period) in a file name is a java package separator. 文件名中的(句点)是java包分隔符。 So i guess you have to first get the right folder and then the file. 所以我想你必须首先得到正确的文件夹,然后是文件。

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

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