从 Eclipse 中外部创建的文件获取存储

Get IStorage from externaly created file in Eclipse

我目前正在 Eclipse Neon 中开发一个编辑器插件。除了使用编辑器打开文件外,一切都完美无缺,这些文件不是在当前 Eclipse 项目内部创建的,而是在工作区外部的文件夹中手动创建的(例如文档)。

在我的实现中,我需要每个要打开的文件的 IStorage。我当前的代码如下所示:

public static IStorage getStorage(IEditorInput editorInput) {
    if (editorInput instanceof IStorageEditorInput) {
      try {
        return ((IStorageEditorInput) editorInput).getStorage();
      }
      catch (CoreException e) {
        throw new RuntimeException(e);
      }
    }
    else if (editorInput instanceof FileStoreEditorInput) {
      try {
        IURIEditorInput uriInput = (IURIEditorInput)editorInput;
        URI uri = uriInput.getURI();
        File file = new File(uri);
        return ((IStorageEditorInput) editorInput).getStorage(); // How to get the IStorage
      }
      catch (CoreException e) {
        throw new RuntimeException(e);
      }
    }
    else {
      throw new IllegalArgumentException("Unknown IEditorInput implementation");
    }
  }

重要的情况是如果 editorInputFileStoreEditorInput 的实例,它在第二个 if 中处理。目前,我从中获取了一个文件,但我不知道如何从文件或 FileStoreEditorInput 本身获取 IStorage

我不知道有什么方法可以为 FileStoreEditorInput 获取 IStorage。除了你可以尝试看看 editorInput.getAdapter( IStorage.class ) returns 是否有用。

但是,您可以自己实现 IStorage 接口。例如:

class FileStorage implements IStorage {
  private final FileStoreEditorInput editorInput;

  FileStorage( FileStoreEditorInput editorInput ) {
    this.editorInput = editorInput;
  }

  @Override
  public <T> T getAdapter( Class<T> adapter ) {
    return Platform.getAdapterManager().getAdapter( this, adapter );
  }

  @Override
  public boolean isReadOnly() {
    return false;
  }

  @Override
  public String getName() {
    return editorInput.getName();
  }

  @Override
  public IPath getFullPath() {
    return new Path( URIUtil.toFile( editorInput.getURI() ).getAbsolutePath() );
  }

  @Override
  public InputStream getContents() {
    try {
      return editorInput.getURI().toURL().openStream();
    } catch( IOException e ) {
      throw new UncheckedIOException( e );
    }
  }
}