How to read data from a file in Eclipse Plug-in?
I'm currently developing a Eclipse plug-in. When called, my plug-in will read the active (currently opened) source file's data and will do some formatting on the source code and then it will update the results to the same active source file.
Now my questions are:
- How to read the data from the active source file? Do I need to get the file location of this file and directly read from there or is there any other way to do it?
- After getting and processing data from above step 1, if I upd开发者_开发知识库ate the output to the active document, will Eclipse throw any IOException? Will Eclipse keep a lock on the source file? (I think it's not, because I have seen other editors update the source file, while it's opened in Eclipse also. But to know it for sure, I'm putting the question here.)
You should use Eclipse's infrastructure for editors and documents. I don't think it's a good idea to change files' contents "behind Eclipse's back".
I'm not an expert on this, but I can give you a code sample to get you started:
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage activePage = window.getActivePage(); // null check omitted
IEditorPart editorPart = activePage.getActiveEditor(); // null check omitted
ITextEditor textEditor = (ITextEditor) editorPart; // casting check omitted
IDocument currentDocument = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
Check out the org.eclipse.jface.text.IDocument
API. It lets you manipulate the text in the current active source file.
精彩评论