许多其他答案让我想到了这个精彩的片段,它声称可以在 Eclipse 中获取当前事件的文件:
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().getActivePart();
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor()
.getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
我完全相信它基于这些问题的结果有效,但是,它总是为我抛出 FileNotFoundException。
这怎么可能?是否有其他方法获取事件文件?
注意:org.eclipse.core.resources
和 org.eclipse.core.runtime
都在我的依赖项列表中,因此 IAdaptable 应该可以正常工作。这是另一个问题中的一个问题。
请您参考如下方法:
编辑器的输入不必支持适应IFile
。输入通常会实现 IFileEditorInput
、IPathEditorInput
、IURIEditorInput
和 ILocationProvider
中的一项或多项。
如果可能,此代码将找到 IFile
或 IPath
:
/**
* Get a file from the editor input if possible.
*
* @param input The editor input
* @return The file or <code>null</code>
*/
public static IFile getFileFromEditorInput(final IEditorInput input)
{
if (input == null)
return null;
if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
final IPath path = getPathFromEditorInput(input);
if (path == null)
return null;
return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
}
/**
* Get the file path from the editor input.
*
* @param input The editor input
* @return The path or <code>null</code>
*/
public static IPath getPathFromEditorInput(final IEditorInput input)
{
if (input instanceof ILocationProvider)
return ((ILocationProvider)input).getPath(input);
if (input instanceof IURIEditorInput)
{
final URI uri = ((IURIEditorInput)input).getURI();
if (uri != null)
{
final IPath path = URIUtil.toPath(uri);
if (path != null)
return path;
}
}
if (input instanceof IFileEditorInput)
{
final IFile file = ((IFileEditorInput)input).getFile();
if (file != null)
return file.getLocation();
}
return null;
}