Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse Plugin Get Code from Current Open File

How can I get the code from the current open file in Eclipse returned in a String or String[]? I need this for a plugin I'm making.

Let's say I have the following code:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

If I have HelloWorld.java open, how do I get that code returned in a String[]? The String[] would contain:

  • "public class HelloWorld {"
  • "public static void main(String[] args) {"
  • "System.out.println("Hello, world!");"
  • "}"
  • "}"
like image 979
nrubin29 Avatar asked Jul 27 '13 16:07

nrubin29


1 Answers

To get the currently edited file's content you can do something like that:

IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); 
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
String content = IOUtils.toString(file.getContents(), file.getCharset());
like image 102
Serge Farny Avatar answered Nov 03 '22 01:11

Serge Farny