【问题标题】:How to get file path information from ICompilationUnit?如何从 ICompilationUnit 获取文件路径信息?
【发布时间】:2012-10-26 16:55:59
【问题描述】:

我可以使用以下代码获取一组 ICompilationUnit,但我需要从 ICompilationUnit 或 IWorkspaceRoot 获取物理文件路径。

我该怎么做?

private static Set<ICompilationUnit> getFiles(String projname)   
throws CoreException {
    IWorkspaceRoot ws = ResourcesPlugin.getWorkspace().getRoot();
    IProject proj = ws.getProject(projname);
    IJavaProject javaProject = JavaCore.create(proj);
    Set<ICompilationUnit> files = new HashSet<ICompilationUnit>();
    javaProject.open(new NullProgressMonitor());
    for (IPackageFragment packFrag : javaProject.getPackageFragments()) {
        for (ICompilationUnit icu : packFrag.getCompilationUnits()) {
            files.add(icu);
        }
    }
    javaProject.close();
    return files;
}

【问题讨论】:

    标签: java eclipse eclipse-plugin filepath


    【解决方案1】:

    向 ICompilationUnit 发送 getUnderlyingResource() 方法。它返回一个 IResource,它可以告诉你它是否是一个文件,如果是,它的文件名和路径的各种形式是什么。

    请注意,也可以返回 null,因此请注意。

    类似这样的:

       // resource is an IResource returned by sending 
       // an iCompilationUnit the getUnderlyingResource() method
    
    if (resource.getType() == IResource.FILE) {
    
        IFile ifile = (IFile) resource;
    
        String path = ifile.getRawLocation().toString();
    
    }
    

    【讨论】:

    • getType() 需要字符串作为参数,getElementType() 不起作用。
    • 你需要像上面一样将getType()发送到IResource()
    • 这种情况,请确保resource不为null,否则会抛出NullPointException。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多