2013-02-20 121 views
1

我已經能夠通過彈出菜單擴展程序成功更新文件的內容我已經在右鍵單擊文件。如何在使用IFile修改文件後指示文件已更改

我想指出文件已被更改並需要保存。目前,文件內容會自動更改並保存。我認爲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; 
} 

回答

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

如果你想要的文件的內容標記爲需要保存,你需要與你想提示爲需要保存在內存中表示進行交互 - 您從中獲得輸入的編輯器。

+0

行 - 我是新來的PDE發展......我一直在關注着,看來,'IWorkbenchPage.setPartState'可能是我的方法爲此使用 - 聽起來是對的嗎? – 2013-02-20 17:39:19

+0

恩,沒有。它應該需要保存,如果它實際上不同於磁盤上的內容。是嗎?如果是這樣,怎麼樣? – nitind 2013-02-20 20:36:21

+0

也許我這樣做的方式是錯誤的......我最終只是試圖更新編輯器中的一些文本,然後用戶可以保存或放棄這些更改(如果他們喜歡的話...)在查找示例時遇到很多問題代碼來做到這一點...... – 2013-02-20 21:46:27

相關問題