Eclipse插件:创建新文件

8

我正在尝试在Eclipse插件中创建一个新文件。它不一定是Java文件,例如可以是HTML文件。

现在我正在执行以下操作:

IProject project = ...;
IFile file = project.getFile("/somepath/somefilename"); // such as file.exists() == false
String contents = "Whatever";
InputStream source = new ByteArrayInputStream(contents.getBytes());
file.create(source, false, null);

该文件已创建,但问题在于它没有被识别为任何类型; 我无法在任何内部编辑器中打开它。 在我重新启动Eclipse之前(刷新或关闭然后重新打开项目都没有帮助)。 重新启动后,该文件可以完美地使用,并在其类型的正确默认编辑器中打开。

是否有任何方法可以调用以使文件摆脱“悬空”状态?

1个回答

7

这个线程确实提到了createFile的调用,但也提到了使用FileEditorInput来打开它:

你应该使用IFile.create(..)IFile.createLink(..)而不是java.io.File。你需要使用IProject.getFile(..)从项目中获取IFile句柄,然后使用该句柄创建文件。
创建文件后,您可以从中创建FileEditorInput,并使用IWorkbenchPage.openEditor(..)在编辑器中打开文件。

现在,这种方法(来自AbstractExampleInstallerWizard)对此有帮助吗?

  protected void openEditor(IFile file, String editorID) throws PartInitException
  {
    IEditorRegistry editorRegistry = getWorkbench().getEditorRegistry();
    if (editorID == null || editorRegistry.findEditor(editorID) == null)
    {
      editorID = getWorkbench().getEditorRegistry().getDefaultEditor(file.getFullPath().toString()).getId();
    }

    IWorkbenchPage page = getWorkbench().getActiveWorkbenchWindow().getActivePage();
    page.openEditor(new FileEditorInput(file), editorID, true, IWorkbenchPage.MATCH_ID);
  }  

同时也可以参考这个SDOModelWizard,它可以在新的IFile上打开编辑器:

  // Open an editor on the new file.
  //
  try
  {
    page.openEditor
      (new FileEditorInput(modelFile),
       workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
  }
  catch (PartInitException exception)
  {
    MessageDialog.openError(workbenchWindow.getShell(), SDOEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
    return false;
  }

确实,用正确的编辑器打开文件就解决了问题。谢谢! - erwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接