需求描述:
实时地远程获得json格式的内容,在本地以可编辑模式打开供用户修改并保存至远程服务器
实现片段:
首先将获得的json内容保存至.metadata目录下,比如保存为in.json,然后在plugin.xml中定义in.json默认的editor:
<editor
name="In/Out Json Editor"
icon="icons/json.gif"
class="myplugin.editors.inout.InOutJsonEditor"
matchingStrategy= "myplugin.editors.inout.InOutJsonEditorMatchingStrategy"
id="myplugin.editors.inout.InOutJsonEditor">
</editor>
然后需要在eclipse的editor中打开非workspace中的file:
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
}
注意这里是如何使用EFS将Java的File类型转换为Eclipse workspace中需要的IResource类型
File inJsonLocalFile = new File(jsonDir);
IPath inJsonLocalPath = Path.fromOSString(inJsonLocalFile.getAbsolutePath());
IFileStore inJsonLocation = EFS.getLocalFileSystem().getStore(inJsonLocalPath);
FileStoreEditorInput inJsonEditorInput = new FileStoreEditorInput(inJsonLocation);
如果报错提示说EFS这个类找不到,记得在dependencies中加入‘org.eclipse.core.filesystem’,如果已经存在,还是报EFS类找不到,删除它重新加入'org.eclipse.core.filesystem'
非本地保存的实现方式:
有没有可能不保存远程得到的string content至本地文件,直接在eclipse的editor中打开呢?其实是可以的,只不过在IWorkbenchPage的openEditor(input, editorID)方法中传入的第一个参数input不是IFileEditorInput类型,而是IStorageEditorInput类型
具体可以参照:How do I open an editor on something that is not a file
这里的StringInput实现了接口IStorageEditorInput,所有的内容可以传入StringInput对象,然后将StringInput作为input参数传入input,那么editorID对应的editor就可以得到input的所有内容。