1

我已经能够通过我在右键单击文件时出现的源菜单下创建的弹出菜单扩展成功更新文件的内容。

我想指出该文件已更改并需要保存。现在,文件内容会自动更改并保存。我认为 IFile.touch 方法会导致文件处于需要保存的状态,但我没有看到这种情况发生。

这是我的代码...

public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
    IEditorInput input = editorPart.getEditorInput();
    InputStream is = null;
    if (input instanceof FileEditorInput) {
        IFile file = ((FileEditorInput) input).getFile();
        try {
            is = file.getContents();
            String originalContents = convertStreamToString(is);
            String newContents = originalContents + "testing changing the contents...";
            InputStream newInput = new ByteArrayInputStream(newContents.getBytes());
            file.setContents(newInput, false, true, null);
            file.touch(null);
        } catch (CoreException e) {
            MessageDialog.openError(
                window.getShell(),
                "Generate Builder Error",
                "An Exception has been thrown when interacting with file " + file.getName() +
                ": " + e.getMessage());
        }
    }
    return null;
}
4

2 回答 2

3

如果您希望将文件的内容标记为需要保存,则需要与要提示需要保存的内存表示进行交互——您从中获取输入的编辑器。

于 2013-02-20T17:17:04.523 回答
0

基于来自 nitind 的帮助和这篇文章 -通过插件命令从 eclipse 编辑器中替换选定的代码- 我能够更新文本编辑器并且文件显示为已修改。关键是使用 ITextEditor 和 IDocumentProvider 而不是 FileEditor。

这是更新的代码...

public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
    if (editorPart instanceof ITextEditor ) {
        ITextEditor editor = (ITextEditor)editorPart;
        IDocumentProvider prov = editor.getDocumentProvider();
        IDocument doc = prov.getDocument( editor.getEditorInput() );
        String className = getClassName(doc.get());
        ISelection sel = editor.getSelectionProvider().getSelection();
        if (sel instanceof TextSelection ) {
            TextSelection textSel = (TextSelection)sel;
            String newText = generateBuilderText(className, textSel.getText());
            try {
                doc.replace(textSel.getOffset(), textSel.getLength(), newText);
            } catch (Exception e) {
                MessageDialog.openError(
                    window.getShell(),
                    "Generate Builder Error",
                    "An Exception has been thrown when attempting to replace " 
                    + "text in editor " + editor.getTitle() +
                    ": " + e.getMessage());
            }
        }
    }
    return null;
}
于 2013-02-21T15:46:22.937 回答