【问题标题】:get the list of source files from existing eclipse project using CDT使用 CDT 从现有 eclipse 项目中获取源文件列表
【发布时间】:2012-09-14 09:33:45
【问题描述】:

我正在开发 CDT eclipse 插件,我正在尝试使用 CDT 代码使用以下代码获取 eclipse 项目资源管理器中存在的源文件列表,结果为 null。

案例1:

IFile[] files2 = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(new URI("file:/"+workingDirectory));
for (IFile file : files2) {
   System.out.println("fullpath " +file.getFullPath());
}

案例2:

IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(getProject().getRawLocationURI());
for (IFile file : files) {
   System.out.println("fullpath " +file.getFullPath());              
}

案例3:

IFile[] files3 = ResourceLookup.findFilesByName(getProject().getFullPath(),ResourcesPlugin.getWorkspace().getRoot().getProjects(),false);
for (IFile file : files3) {
   System.out.println("fullpath " +file.getFullPath());
}

案例4:

IFolder srcFolder = project.getFolder("src");

案例 1 ,2,3 给我输出 null,我期待文件列表; 在案例 4 中:我正在获取“helloworld/src”文件的列表,但我希望从现有项目中获取文件意味着主根目录,例如:“helloworld” 请就此向我提出建议。

【问题讨论】:

    标签: eclipse-cdt


    【解决方案1】:

    您可以使用 IResourceVisitor 浏览工作空间资源树,也可以浏览 CDT 模型:

    private void findSourceFiles(final IProject project) {
        final ICProject cproject = CoreModel.getDefault().create(project);
        if (cproject != null) {
            try {
                cproject.accept(new ICElementVisitor() {
    
                    @Override
                    public boolean visit(final ICElement element) throws CoreException {
                        if (element.getElementType() == ICElement.C_UNIT) {
                            ITranslationUnit unit = (ITranslationUnit) element;
                            if (unit.isSourceUnit()) {
                                System.out.printf("%s, %s, %s\n", element.getElementName(), element.getClass(), element
                                        .getUnderlyingResource().getFullPath());
                            }
                            return false;
                        } else {
                            return true;
                        }
                    }
                });
            } catch (final CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    请注意,源文件可能比您实际需要的要多(例如,您可能不关心系统的标头) - 您可以通过检查底层资源是什么来过滤它们。

    【讨论】:

    • Eugene,感谢您的回复;嗯,它列出了项目源文件,如果是单个项目,但我的情况是我有标准 make 项目,在主标准 make 项目中我又创建了一个项目,我想要主项目的源文件列表;也使用给定的代码列出内部项目的源文件;但我只想获取相关项目的源文件;请建议;
    • @AnilKumar 看看 IResourceVisitor(和 IResource::accept)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多