【问题标题】:Eclipse plugin: create a new fileEclipse插件:创建一个新文件
【发布时间】:2014-09-03 19:27:02
【问题描述】:

我正在尝试在 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(刷新或关闭然后打开项目没有帮助)。重新启动后,该文件完全可用,并在其类型的正确默认编辑器中打开。

我需要调用任何方法来使文件脱离“边缘”状态吗?

【问题讨论】:

    标签: eclipse file eclipse-plugin


    【解决方案1】:

    thread 确实提到了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;
      }
    

    【讨论】:

    • 确实,在正确的编辑器中打开文件就可以了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    相关资源
    最近更新 更多