【问题标题】:How to format which is in String to java format如何将字符串格式转换为java格式
【发布时间】:2013-09-22 21:48:15
【问题描述】:

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

但我想以我尝试使用以下代码的 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) 行收到空指针异常 pagehandlercontent 包含一个转换为字符串格式的文件 textEdit.apply(doc) 不接受某些特殊字符。这就是我得到空指针异常的原因。 还有其他方法吗?

【问题讨论】:

  • “但我想以 java 格式显示文本” 你这是什么意思?
  • 我正在获取文件并将其转换为字符串,并在 swt 文本框中显示字符串我希望文本以正确的 java 格式显示
  • 你的意思是缩进或代码高亮之类的东西?
  • 来自CodeFormatter.format() javadoc:如果给定的字符串无法格式化,则返回 null。如果您包含有关您的 pagehandlerContent 的更多信息,将会很有帮助。
  • 什么是“java格式”??

标签: java swt jface


【解决方案1】:

您是否尝试过使用以下内容:

import org.apache.commons.lang3.StringEscapeUtils;

StringEscapeUtils.escapeJava(string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2020-11-20
    • 2011-09-06
    相关资源
    最近更新 更多