簡體   English   中英

Canonical獲取活動文件代碼拋出FileNotFound異常

[英]Canonical get active file code throwing FileNotFound exception

許多其他答案讓我得到了這個精彩的片段,聲稱在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.resourcesorg.eclipse.core.runtime都在我的依賴列表中,所以IAdaptable應該可以正常工作。 這是另一個問題。

編輯器的輸入不必支持適應IFile 輸入通常會實現一個或多個的IFileEditorInputIPathEditorInputIURIEditorInputILocationProvider

如果可能,此代碼將找到IFileIPath

/**
 * 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM