使用IFile修改文件后,如何指示文件已更改

时间:2013-02-20 16:56:20

标签: eclipse eclipse-plugin

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

我想表明该文件已被更改,需要保存。此时,文件内容会自动更改并保存。我认为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;
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

基于nitind的帮助和这篇文章 - Replace selected code from eclipse editor thru plugin comand - 我能够更新文本编辑器,文件显示为已修改。关键是使用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;
}