如何从String
或String[]
中返回的Eclipse中的当前打开文件中获取代码?我需要这个用于我正在制作的插件。
假设我有以下代码:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
如果我打开HelloWorld.java,如何在String[]
中返回该代码? String[]
将包含:
答案 0 :(得分: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());