6

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!");"
  • "}"
  • "}"
nrubin29
  • 1,522
  • 5
  • 25
  • 53

1 Answers1

13

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());
Serge Farny
  • 932
  • 10
  • 22
  • 1
    `The method getAdapter(Class) is undefined for the type IEditorInput` – nrubin29 Jul 27 '13 at 19:23
  • 2
    Also no class IFile and IOUtils. – nrubin29 Jul 27 '13 at 19:24
  • 2
    IEditorInput implements the IAdaptable interface, so getAdapter() should be there. IFile is in org.eclipse.core.resources. IOUtils is a class in Apache Common libraries. You can convert the InputStream to a String using others methods if you prefer. Which version of Eclipse are you using/targeting ? – Serge Farny Jul 27 '13 at 19:34
  • To add "org.eclipse.core.resources", import is NOT enough. You have to add it as a dependency in your plugin MANIFEST.MF – Serge Farny Jul 27 '13 at 19:36
  • There is nothing to download, you already have it (it a basic component of Eclipse). Add it in the MANIFEST.MF `Require-Bundle` list. (this code snippet is working for indigo.) – Serge Farny Jul 27 '13 at 20:33
  • 2
    This code does get the **file content** —which is what was asked for. In some cases, one might want the **editor content**, instead —that would be a different question, though. In both cases, there is the presumption that "code" means **text**, but, in general, neither a file nor editor necessarily have text. – Tom Blodget Jul 27 '13 at 22:11