【问题标题】:How to properly set the content of an IFile in Eclipse plugin when the editor is opened打开编辑器时如何在 Eclipse 插件中正确设置 IFile 的内容
【发布时间】:2019-04-15 21:27:14
【问题描述】:

我正在使用以下代码来设置 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() 方法),但这没有帮助。

有没有办法避免这个警告?

【问题讨论】:

  • 这并不是文件在 Eclipse 之外被修改的警告,只是在编辑器之外。

标签: java eclipse-plugin eclipse-rcp


【解决方案1】:

将您的方法封装在 WorkspaceModifyOperation 中。

【讨论】:

  • 感谢您的建议,看起来在不同的线程中批量运行操作,但我仍然收到相同的警告
  • 是的,调用 setContents() 后可以看到编辑器脏了
  • 不,我的意思是在你真正触摸文件之前。
  • 这是你自己的编辑器类吗?非脏编辑器应该会自动刷新。
  • 不是,是在Eclipse自带的JSON编辑器中打开的.json文件
【解决方案2】:

编辑器的反应看起来是正确的,因为在绑定到编辑器实例的 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);
                    }
                }
            }
        }

老实说,我不明白你试图涵盖的场景,可能有更好的方法来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    相关资源
    最近更新 更多