2014-09-22 115 views
2

我正在创建一个eclipse插件,它需要检索在当前工作区窗口中打开的所有文件的路径/文件名。需要在当前eclipse工作区中查找文件的文件路径

我写的代码,成功地检索当前打开的java文件的文件名,但无法检索所有其他文件类型,如XML的路径/文件,JSP,CSS等

代码我已经使用至今: -

IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); 

    IEditorReference[] ref = page.getEditorReferences(); 

    List<IEditorReference> javaEditors = new ArrayList<IEditorReference>(); 

    //Checks if all the reference id's match the active editor's id 
    for (IEditorReference reference : ref) { 
     if ("org.eclipse.jdt.ui.CompilationUnitEditor".equals(reference.getId())){ 
      javaEditors.add(reference); 
     } 
    } 

    if(javaEditors != null){ 
     for(IEditorReference aRef : javaEditors){ 
      System.out.println("File info: " + aRef.getName()); 
     } 
    } 

我需要的是帮助 - 检索当前打开的工作区/编辑器打开的所有文件(任何文件类型)(文件路径+文件名)。上面的代码只能让我获得在当前编辑器中打开的Java类的文件名。

+0

注意的是并不是每个编辑器会与实际文件相关联,或者只用1个文件的事实。一些编辑可以处理a)根本没有文件(一个“逻辑”结构,它由文件以外的东西支持),或b)多个文件。 @ greg-449的答案通过返回null来处理这些问题;根据您的要求,您可能需要做其他事情。 – 2014-09-22 16:12:52

回答

2

这应该处理这个实际上是在编辑一个文件中的所有编辑:

IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); 

IEditorReference[] refs = page.getEditorReferences(); 

for (IEditorReference reference : refs) { 

    IEditorInput input = reference.gtEditorInput(); 

    IPath path = getPathFromEditorInput(input); 
    if (path != null) 
    { 
     System.out.println(path.toOSString()); 
    } 
} 


private static IPath getPathFromEditorInput(IEditorInput input) 
{ 
    if (input instanceof ILocationProvider) 
    return ((ILocationProvider)input).getPath(input); 

    if (input instanceof IURIEditorInput) 
    { 
    URI uri = ((IURIEditorInput)input).getURI(); 
    if (uri != null) 
     { 
     IPath path = URIUtil.toPath(uri); 
     if (path != null) 
      return path; 
     } 
    } 

    if (input instanceof IFileEditorInput) 
    { 
    IFile file = ((IFileEditorInput)input).getFile(); 
    if (file != null) 
     return file.getLocation(); 
    } 

    return null; 
} 
+0

为了保持健壮性,应该尽量调整IEditorInput而不是调用'instanceof'。有些编辑可能会使用不能直接实现这些接口的自适应输入类型。 – 2014-09-22 16:14:22

+0

另外,'IFile#getLocation()'用于* on-disk *位置,而不是工作空间中的路径(实际上可能不在工作空间的目录下)。使用'IFile#getFullPath()'。 FWIW,org.eclipse.core.resources及其API在区分位置和路径之间的区别方面相对一致。 – nitind 2014-09-22 16:57:08

+0

@nitind有些编辑器可能正在编辑不在工作区中的文件。我的代码返回一切的完整路径。 – 2014-09-22 17:02:29