【问题标题】:Get the absolute path of the currently edited file in Eclipse获取Eclipse中当前编辑文件的绝对路径
【发布时间】:2010-09-22 21:54:25
【问题描述】:

我想写一个插件来处理当前在 Eclipse 中编辑的文件。但我不确定如何正确获取文件的完整路径。

这就是我现在所做的:

IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
    getAdapter(IFile.class);

现在我有一个 IFile 对象,我可以检索它的路径:

file.getFullPath().toOSString();

但是,这仍然只给了我相对于工作空间的路径。我怎样才能从中获得绝对路径?

【问题讨论】:

    标签: java eclipse eclipse-plugin eclipse-api


    【解决方案1】:

    对我来说,这个运行没问题。

    IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    文件文件 = workSpaceRoot.getRawLocation().makeAbsolute().toFile();

    来自该位置的文件列表:

    文件[] 文件 = file.listFiles();

    【讨论】:

      【解决方案2】:

      看起来你想要IResource.getRawLocation()。这会返回一个IPath,如果你想更加确定你有一个绝对路径,它也有一个makeAbsolute() 方法。

      【讨论】:

      • IResource.getRawLocation() 的链接现在已更改。
      【解决方案3】:

      对我有用(并且我测试过!)的答案是:

      // Get the currently selected file from the editor
      IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); 
      IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
      if (file == null) throw new FileNotFoundException();
      String path = file.getRawLocation().toOSString();
      System.out.println("path: " + path);
      

      【讨论】:

        【解决方案4】:

        我认为对 Java 更友好的解决方案是使用以下内容:

        IResource.getLocation().toFile()
        

        这利用了 IPath API(getLocation() 部分)并将返回一个 java.io.File 实例。当然,其他答案可能也会让你到达你想去的地方。

        顺便说一句,我发现 IDE 类 (org.eclipse.ui.ide.IDE) 对于编辑器来说是一个有用的实用资源。

        【讨论】:

          【解决方案5】:
          IWorkspace ws      = ResourcesPlugin.getWorkspace();  
          IProject   project = ws.getRoot().getProject("*project_name*");
          
          IPath location = new Path(editor.getTitleToolTip());  
          IFile file     = project.getFile(location.lastSegment());
          
          into file.getLocationURI() it's the absolute path
          

          【讨论】:

            【解决方案6】:

            我通常调用返回 IPath 的 IFile.getLocation(),然后调用 IPath.toOSString()。

            file.getLocation().toOSString()
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-04-24
              • 2010-09-18
              • 1970-01-01
              • 2012-05-10
              相关资源
              最近更新 更多