[英]How to properly set the content of an IFile in Eclipse plugin when the editor is opened
我正在使用以下代码来设置 IFile 的内容:
public static IFile updateFile(IFile file, String content) {
if (file.exists()) {
InputStream source = new ByteArrayInputStream(content.getBytes());
try {
file.setContents(source, IResource.FORCE, new NullProgressMonitor());
source.close();
} catch (CoreException | IOException e) {
e.printStackTrace();
}
}
return file;
}
当文件未在编辑器中打开时,这可以正常工作,但是如果文件被打开,我会收到以下警告,就像文件在 Eclipse 之外被修改一样:
我尝试在调用setContents()
之前和之后刷新文件(通过调用refreshLocal()
方法),但这没有帮助。
有没有办法避免这个警告?
将您的方法包装在WorkspaceModifyOperation
。
编辑器反应看起来是正确的,因为在绑定到编辑器实例的 org.eclipse.jface.text.IDocument 之外有一个修改。
正确的方法不是修改文件内容,而是修改代表文件内容的“模型”实例,例如 JDT 的IJavaElement
。
也可以尝试直接操作文档内容(需要打磨制作):
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorReference[] editorReferences = page.getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
IEditorPart editorPart = editorReference.getEditor(false/*do not restore*/);
IEditorInput editorInput = editorPart.getEditorInput();
//skip editors that are not related
if (inputAffected(editorInput)) {
continue;
}
if (editorPart instanceof AbstractTextEditor) {
AbstractTextEditor textEditor = (AbstractTextEditor) editorPart;
IDocument document = textEditor.getDocumentProvider().getDocument(editorInput);
document.set(content);
}
}
}
}
老实说,我不明白您要涵盖的场景,可能有更好的方法来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.