如何在打开编辑器时正确设置Eclipse插件中的IFile内容

问题描述 投票:1回答:2

我正在使用以下代码来设置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之外修改了文件一样:

enter image description here

我在调用refreshLocal()之前和之后尝试刷新文件(通过调用setContents()方法),但这没有帮助。

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

java eclipse-plugin eclipse-rcp
2个回答
1
投票

将你的方法包裹在WorkspaceModifyOperation中。


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.