6

如何从 Eclipse 中返回的当前打开文件中获取代码StringString[]?我正在制作的插件需要这个。

假设我有以下代码:

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

如果我打开了 HelloWorld.java,我如何在 a 中返回该代码String[]?将String[]包含:

  • “公共课 HelloWorld {”
  • “公共静态无效主(字符串[]参数){”
  • "System.out.println("你好,世界!");"
  • “}”
  • “}”
4

1 回答 1

13

要获取当前编辑文件的内容,您可以执行以下操作:

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());
于 2013-07-27T19:18:21.493 回答