🚀 java处理富文本内容
需求:富文本框内容在列表或者简述进行去标签展示
import com.alibaba.fastjson.JSON;
import com.leesky.ezframework.execl.util.StringUtils;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* 处理富文本
*/
public class Html2Text extends HTMLEditorKit.ParserCallback {
private static class InnerClass{
private static final Html2Text html2Text = new Html2Text();
}
public static Html2Text getInstance(){
return InnerClass.html2Text;
}
StringBuffer stringBuffer;
public Html2Text() {}
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();
// the third parameter is TRUE to ignore charset directive
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();
}
/**
* 去除标签
* @param str
* @return
*/
public static String getContent(String str) {
if (StringUtils.isEmpty(str)) return "";
try {
InnerClass.html2Text.parse(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return InnerClass.html2Text.getText();
}
/**
* 截取字符串,判断长度保留
* @param str 富文本
* @param len 长度
* @return
*/
public static String getPartialContent(String str, int len) {
if (StringUtils.isEmpty(str)) return "";
// 去标签化
str = getContent(str);
// 判断长度若小于则赋值本身长度
if (str.length() < len)
len = str.length();
return str.substring(0, len);
}
public static void main(String[] args) {
String str = "<title>java将富文本字符串(HTML)转为文本(Text)。</title>";
System.out.println(getContent(str));
System.out.println(getPartialContent(str, 100));
}
}
本文作者:玩单机的零度
本文链接:https://www.cnblogs.com/cxyfyf/p/16969117.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步