以编程方式将文件加载到TextEditor中,而不是在工作区中

时间:2012-09-27 08:40:10

标签: eclipse file editor text-editor rcp

有没有办法在工作区外加载文件? 这是我发现的:

IFile fileToBeOpened = ...;
IEditorInput editorInput = new FileEditorInput(fileToBeOpened);
IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEdtior");

这里的问题是第一行。我想编辑的文件属于java.io.File类型。但是无法将其转换为IFile实例。如何将java.io.File作为编辑器的输入传递?

1 个答案:

答案 0 :(得分:2)

要打开外部文件,请按照此处的说明操作 http://wiki.eclipse.org/FAQ_How_do_I_open_an_editor_programmatically%3F

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}