陶杰
2024-08-22 ee9032d9baf5f33e376d2d2699136e0a7b26bec7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.mzl.flower.utils;
 
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
 
public class Html2TextUtil extends HTMLEditorKit.ParserCallback {
 
    private static Html2TextUtil html2Text = new Html2TextUtil();
 
    StringBuffer s;
 
    public Html2TextUtil() {
    }
 
    public void parse(String str) throws IOException {
 
        InputStream iin = new ByteArrayInputStream(str.getBytes());
        Reader in = new InputStreamReader(iin);
        s = new StringBuffer();
        ParserDelegator delegator = new ParserDelegator();
        delegator.parse(in, this, Boolean.TRUE);
        iin.close();
        in.close();
    }
 
    public void handleText(char[] text, int pos) {
        s.append(text);
    }
 
    public String getText() {
        return s.toString();
    }
 
    public static String getContent(String str) {
        if(str == null || "".equals(str.trim())){
            return str;
        }
        try {
            html2Text.parse(str);
        } catch (IOException e) {
        }
        return html2Text.getText();
    }
}