获取Eclipse中当前编辑文件的绝对路径
我想编写一个插件,用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();