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

这就是我现在所做的:

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

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

file.getFullPath().toOSString();

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

有帮助吗?

解决方案

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

其他提示

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

IResource.getLocation().toFile()

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

在切线上,我发现IDE类(org.eclipse.ui.ide.IDE)是编辑器的一个有用的实用程序资源。

对我有用的答案(我测试了它!)是:

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

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

file.getLocation().toOSString()
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

对我来说,这运行正常。

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

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

此位置的文件列表:

File [] files = file.listFiles();

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top