unfuse
unfuse

Reputation: 35

Canonical get active file code throwing FileNotFound exception

Many other answers led me to this wonderful snippet, which claims to get the currently active file in 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();

I fully believe it works based on results from those questions, however, it always throws a FileNotFoundException for me.

How can this be? Is there another way to get the active file?

Note: org.eclipse.core.resources and org.eclipse.core.runtime are both in my dependency list, so IAdaptable should work just fine. This was an issue in another question.

Upvotes: 3

Views: 63

Answers (1)

greg-449
greg-449

Reputation: 111217

The input to an editor does not have to support adapting to IFile. The input will usually implement one or more of IFileEditorInput, IPathEditorInput, IURIEditorInput and ILocationProvider.

This code will find the IFile or IPath if possible:

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

Upvotes: 1

Related Questions