【问题标题】:Get IProject from a custom IStorage implementation从自定义 IStorage 实现中获取 IProject
【发布时间】:2016-12-13 11:16:38
【问题描述】:

我目前正在开发一个 Eclipse Neon 编辑器插件。目前我正在尝试能够从文件系统中打开文件,这些文件不是在 Eclipse 中创建的。为此,我需要通过以下方法获得IProject:

public static IProject getProject(IStorage storage) {
    if (storage instanceof IFile) {
      return ((IFile) storage).getProject();
    }
    else if (storage instanceof IJarEntryResource) {
      return ((IJarEntryResource) storage).getPackageFragmentRoot().getJavaProject().getProject();
    }
    else if (storage instanceof FileStorage) {
      // ????
    }
    else {
      throw new IllegalArgumentException("Unknown IStorage implementation");
    }
  }

这里的FileStorage 是IStorage 接口的一个自己的实现。看起来像这样:

public 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 );
    }
  }
}

有什么方法可以从这个FileStorage 获得IProject?

【问题讨论】:

  • 如果文件不在项目中,则无法获得 IProject。

标签: java eclipse eclipse-plugin eclipse-rcp


【解决方案1】:

您可以尝试使用以下方法获取文件的IFile:

IPath path = ... absolute path to the file

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile file = root.getFileForLocation(path);
if (file != null) {
  IProject project = file.getProject();
  ...
}

但这仅适用于工作区中的文件。对于工作区之外的任何内容,您都不能拥有项目。

【讨论】:

    【解决方案2】:

    简而言之:不会。FileStorage 类旨在代表位于工作区外部的文件的IStorage 实例。因此它们不包含在任何工作区项目中,并且无法为它们获取IProject。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多