2009-10-26 105 views
8

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

现在我这样做:

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”状态之外?

回答

7

thread确实提到了createFile电话,但也指FileEditorInput打开它:

相反的java.io.File,你应该使用IFile.create(..)IFile.createLink(..)。您需要先使用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; 
    } 
+0

的确,打开文件在正确的编辑器没有的伎俩。谢谢! – erwan 2009-10-26 16:15:25