富文本中文字部分提取


//富文本編輯器內的內容保存到數據庫后是一段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);
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM