我正在开发向导页面。在该页面中,我将文件转换为String并将其显示在文本框中

但是我想以Java格式显示文本
我尝试了以下代码

import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
    public class FormatterTest {
        public static void main(String[] args) {
            String code = pagehandlerContent; //the file which im getting and saving it in string
            CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);
            TextEdit textEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, null);
            IDocument doc = new Document(code);
            try {
                textEdit.apply(doc);
                System.out.println(doc.get());
            } catch (MalformedTreeException e) {
                e.printStackTrace();
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    }


但是我在textEdit.apply(doc)行上得到了空指针异常

最佳答案

您的CodeFormatter为空

CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);

注意:我无法发表评论

08-27 15:17