Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse plugin: create a new file

I'm trying to create a new file in an eclipse plugin. It's not necessarily a Java file, it can be an HTML file for example.

Right now I'm doing this:

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

The file gets created, but the problem is that it doesn't get recognized as any type; I can't open it in any internal editor. That's until I restart Eclipse (refresh or close then open the project doesn't help). After a restart, the file is perfectly usable and opens in the correct default editor for its type.

Is there any method I need to call to get the file outside of that "limbo" state?

like image 673
erwan Avatar asked Oct 26 '09 10:10

erwan


1 Answers

That thread does mention the createFile call, but also refers to a FileEditorInput to open it:

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.

Now, would that kind of method (from this AbstractExampleInstallerWizard) be of any help in this case?

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

See also this SDOModelWizard opening an editor on a new 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;
  }
like image 140
VonC Avatar answered Oct 20 '22 05:10

VonC