【问题标题】:Need to find file path of files in current eclipse workspace需要在当前eclipse工作区中查找文件的文件路径
【发布时间】:2014-09-22 15:42:11
【问题描述】:

我正在创建一个 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 类的文件名。

【问题讨论】:

  • 请注意,并非每个编辑器都会与实际文件相关联,或者仅与 1 个文件相关联。一些编辑器可能正在处理 a) 根本没有文件(由文件以外的东西支持的“逻辑”结构),或 b) 多个文件。 @greg-449 的答案只返回 null;根据您的要求,您可能需要做其他事情。

标签: java eclipse eclipse-plugin


【解决方案1】:

这应该处理所有实际编辑单个文件的编辑器:

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;
}

【讨论】:

  • 要真正健壮,它可能应该尝试调整 IEditorInput 而不是调用instanceof。一些编辑器可能使用不直接实现这些接口的自适应输入类型。
  • 另外,IFile#getLocation() 用于 磁盘上 位置,而不是工作空间中的路径(实际上可能不在工作空间的目录下)。使用IFile#getFullPath()。 FWIW、org.eclipse.core.resources 及其 API 在位置和路径之间的这种区别上相对一致。
  • @nitind 一些编辑器可能正在编辑不在工作区中的文件。我的代码返回所有内容的完整路径。
  • @greg-449 除了工作区中的路径与磁盘位置不同之外,这与您编写的任何内容都不矛盾。一旦您确定输入来自IResource,它们就是不同的 API 调用。
  • 感谢以上解决方案!使用上面提供的代码,我能够检索文件路径+名称。这正是我所需要的! (上面的代码运行需要一些包,并且没有被插件依赖项覆盖,但是通过一些挖掘我能够得到它)。
猜你喜欢
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 2020-05-24
相关资源
最近更新 更多