[英]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.