2013-10-08 111 views
8

我正在使用eclipse插件,其中我必須從項目資源管理器中打開文件。 假設我在項目瀏覽器中有一個項目ABC。右鍵點擊項目後,我有一個選項來運行我的插件工具。處理後,我得到了一些結果,如檢查文件xyz.java。eclipse插件如何通過代碼打開IDE中的文件

現在我想通過代碼

來打開IDE這個文件我用這

File absolute = new File("/Decider.java"); 
File file = new File("/Decider.java"); 
IFileStore fileOnLocalDisk = EFS.getLocalFileSystem().getStore(absolute.toURI()); 

FileStoreEditorInput editorInput = new FileStoreEditorInput(fileOnLocalDisk); 

IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); 
IWorkbenchPage page = window.getActivePage(); 

try { 
    page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEditor");   

    page.openEditor(editorInput, "MyEditor.editor");   

     IFileStore fileStore = EFS.getLocalFileSystem().getStore(absolute.toURI()); 
     IDE.openEditorOnFileStore(page, fileStore); 

     } catch (PartInitException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    try { 
     System.out.println(file.getCanonicalPath()); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 


    IPath path = new Path(" /DirectoryReader.java"); 
    IFile sampleFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path); 

    IEditorInput editorInput1 = new FileEditorInput(sampleFile); 
    IWorkbenchWindow window1=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); 
    IWorkbenchPage page1 = window1.getActivePage(); 
    try { 
     page1.openEditor(editorInput1, "org.eclipse.ui.DefaultTextEdtior"); 
    } catch (PartInitException e1) { 

     e1.printStackTrace(); 
    } 

這裏是創建一個名爲決勝局在c盤的新文件,這意味着它才獲得了錯誤的道路。

但是當我在一些獨立的java文件中使用路徑代碼作爲正常的JAVA項目它正在獲得正確的路徑。

+4

出於好奇,爲什麼這會被投票? –

+0

有人可以給我一個簡單的想法或方向前進 – user2379020

+0

我不清楚你在問什麼。你只想打開項目文件或特定編輯器的默認編輯器,或者什麼? –

回答

8

對於工作區中的文件,您應該使用IFile。如果您有來自Project Explorer的選擇或其他視圖應該已經是IFile或可以修改爲IFile

如果您只有工作區相對路徑,請使用ResourcesPlugin.getWorkspace().getRoot().getFile(path)(路徑將包含項目)。

要打開該文件的內容的默認編輯器使用

IDE.openEditor(page, file, true); 

打開特定的編輯器中使用

IDE.openEditor(page, file, "editor id"); 

IDE是org.eclipse.ui.ide.IDE。

+0

是否可以在特定行打開編輯器? – KrzyH

+0

@KrzyH一般來說,不,你不能在特定的行打開編輯器 - 有些編輯甚至沒有行的概念。 'IDE.openEditor'不會返回已打開的'IEditorPart',實現'ITextEditor'的編輯器有一個'selectAndReveal'方法,它顯示文件中的偏移量。 –