简体   繁体   English

如何将字符串格式转换为Java格式

[英]How to format which is in String to java format

I am developing a wizard page. 我正在开发向导页面。 In that page i am converting a file into String and displaying it in the text box 在该页面中,我将文件转换为String并将其显示在文本框中

But I want to display the text in a java format I have tried with the below code 但是我想以下面的代码尝试的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();
            }
        }
    }

but I am getting null pointer exception at textEdit.apply(doc) line pagehandlercontent contains a file which is converted into string format textEdit.apply(doc) is not accepting some special characters. 但是我在textEdit.apply(doc)行的pagehandlercontent包含空指针异常中包含一个文件,该文件已转换为字符串格式textEdit.apply(doc)不接受某些特殊字符。 that is the reason im getting null pointer exception. 这就是我得到空指针异常的原因。 Is there any other way to do it? 还有其他方法吗?

Have you tried using the following: 您是否尝试过使用以下内容:

import org.apache.commons.lang3.StringEscapeUtils;

StringEscapeUtils.escapeJava(string)

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

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