富文本中文字部分提取

//富文本编辑器内的内容保存到数据库后是一段html代码,先因某些需求需要去掉其中的样式等内容,只保留文字,代码如下:
public class HtmlToText extends HTMLEditorKit.ParserCallback {
    private static HtmlToText html2Text = new HtmlToText();
    StringBuffer stringBuffer;
    private HtmlToText() {
    }
    public void parse(String str) throws IOException {
        InputStream iin = new ByteArrayInputStream(str.getBytes());
        Reader in = new InputStreamReader(iin);
        stringBuffer = new StringBuffer();
        ParserDelegator delegator = new ParserDelegator();
        delegator.parse(in, this, Boolean.TRUE);
        iin.close();
        in.close();
    }
    public void handleText(char[] text, int pos) {
        stringBuffer.append(text);
    }
    public String getText() {
        return stringBuffer.toString();
    }
    public static String getContent(String str) {
        try {
            html2Text.parse(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html2Text.getText();
    }
    public static void main(String[] args) {
        String text = HtmlToText.getContent("你的富文本字符串");
        System.out.println(text);
    }
}

  

posted @ 2020-11-05 09:04  守望一心  阅读(988)  评论(0编辑  收藏  举报