简体   繁体   English

Eclipse插件从当前打开的文件中获取代码

[英]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[] ? 如何从StringString[]返回的Eclipse中的当前打开文件中获取代码? 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[] ? 如果我打开HelloWorld.java,如何在String[]返回该代码? The String[] would contain: String[]将包含:

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

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM