Eclipse插件: create a new file

标签 eclipse file eclipse-plugin

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

是否需要调用任何方法才能使文件脱离“limbo”状态?

最佳答案

那个thread确实提到了 createFile 调用,但也引用了 FileEditorInput 来打开它:

Instead of java.io.File, you should use IFile.create(..) or IFile.createLink(..). You will need to get an IFile handle from the project using IProject.getFile(..) first, then create the file using that handle.
Once the file is created you can create FileEditorInput from it and use IWorkbenchPage.openEditor(..) to open the file in an editor.

现在,这种方法(来自 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;
  }

关于Eclipse插件: create a new file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1624054/

相关文章:

java - Intellij 空 R 文件

bash - 在 bash 脚本中,是否可以将由后台进程计算的值分配给变量?

eclipse - 如何更改 Eclipse Git 插件中的默认作者和提交者?

java - 在 Eclipse 上运行斯坦福作业时出现问题

java - 在主屏幕上播放音乐

java - 将-source设置为1.5,显然设置为1.3

java - 使用 BufferedOutputStream 创建大文件需要很长时间

file - Matlab命令访问每个文件的最后一行?

java - 哪个是eclipse kepler最好的html/css/javascript/jquery文本编辑器插件?

eclipse - 停止 eclipse 添加 @Overide 注释