在Eclipse中获取当前正在编辑文件的绝对路径

17

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

这是我现在所做的:

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

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

file.getFullPath().toOSString();

然而,这仅仅给了我相对于工作区的路径。如何从中获取绝对路径?

6个回答

22

看起来您想使用 IResource.getRawLocation()。该方法返回一个IPath对象,如果您想确保得到绝对路径,可以使用makeAbsolute() 方法。


IResource.getRawLocation() 的链接现在已经更改。 - Coder

6
我认为更符合Java的解决方案是使用以下代码:
IResource.getLocation().toFile()

这利用了IPath API(即getLocation()部分),并将返回一个java.io.File实例。当然,其他答案可能也能帮助你达到目标。

顺便提一下,我发现IDE类(org.eclipse.ui.ide.IDE)在编辑器方面是一个有用的工具资源。


5

对我起作用的答案是(我已经测试过了!):

// 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);

1
通常我会调用IFile.getLocation()方法,它会返回一个IPath对象,然后再调用IPath.toOSString()方法。
file.getLocation().toOSString()

0
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

-2

对我来说,这个运行正常。

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

File file = workSpaceRoot.getRawLocation().makeAbsolute().toFile();

从此位置获取文件列表:

File[] files = file.listFiles();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接