简体   繁体   中英

How to properly set the content of an IFile in Eclipse plugin when the editor is opened

I'm using the following code to set the content of an 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;
}

This works fine when the file is not opened in the editor, but if the file is opened I get the following warning as if the file was modified outside of Eclipse:

在此处输入图片说明

I tried to refresh the file (by calling refreshLocal() method) before and after calling setContents() but that didn't help.

Is there a way to avoid this warning?

将您的方法包装在WorkspaceModifyOperation

The editor reaction looks correct, because there is a modification outside of org.eclipse.jface.text.IDocument that bound to the editor instance.

The right approach will be to modify not the file content, but an instance of "model" that represents the file content, something like IJavaElement for JDT.

Also you can try to manipulate the document content directly (needs polishing for production):

        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);
                    }
                }
            }
        }

Honestly, I do not understand the scenario you are trying to cover, probably there are better ways to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM