Java中,从Html代码中提取纯文本字符串,纯文本段落及坐标Java工具类
Java中,从Html代码中提取纯文本字符串,方法有很多种。
下面重点使用Java自带工具类,如何获取纯文本段及段在html代码中的坐标,直接上代码。
public class Html2TextUtil extends HTMLEditorKit.ParserCallback { private StringBuffer stringBuffer; private List<String> stringBufferList; private List<Integer> stringBufferPos; private static Html2TextUtil html2Text = new Html2TextUtil(); public Html2TextUtil() { } public void parse(String str) { InputStream iin = new ByteArrayInputStream(str.getBytes()); Reader in = new InputStreamReader(iin); stringBuffer = new StringBuffer(); stringBufferList=new ArrayList<String>(); stringBufferPos=new ArrayList<Integer>(); ParserDelegator delegator = new ParserDelegator(); try { delegator.parse(in, this, Boolean.TRUE); }catch (Exception e){ }finally { if(in !=null){ try { in.close(); }catch (Exception ee){ } } if(iin !=null){ try { iin.close(); }catch (Exception ee){ } } } } public void handleText(char[] text, int pos) { String textStr=String.valueOf(text); if(textStr!=null&&!"".equals(textStr)){ stringBufferList.add(textStr+"//坐标为:"+pos); stringBufferPos.add(pos); } stringBuffer.append(text); } public String getText() { return stringBuffer.toString(); } public Map<String,Object> getSplitText() { Map<String,Object> map=new Hashtable<String,Object>(); map.put("text",stringBuffer.toString()); map.put("textList",stringBufferList); map.put("textPos",stringBufferPos); return map; } public void flush() throws BadLocationException { } public void handleComment(char[] var1, int var2) { } public void handleStartTag(HTML.Tag var1, MutableAttributeSet var2, int var3) { } public void handleEndTag(HTML.Tag var1, int var2) { } public void handleSimpleTag(HTML.Tag var1, MutableAttributeSet var2, int var3) { } public void handleError(String var1, int var2) { } public void handleEndOfLineString(String var1) { } public static String getContent(String str) { html2Text.parse(str); return html2Text.getText(); } public static Map<String,Object> getContentMap(String str) { html2Text.parse(str); return html2Text.getSplitText(); } public static void main(String[] args){ String s1 = "<p></p><p>考生注意:</p><p style=\"text-indent: 2em;\">1.本试卷分选择题和非选择题两部分。满分100分,考试时间90分钟。</p><p style=\"text-indent: 2em;\">2.答题前,考生务必用直径0. 5毫米黑色墨水签字笔将密封线内项目填写清楚。</p>"; String result=new Html2TextUtil().getContent(s1); System.out.println("【原始html为】:"+s1); System.out.println("【纯文本字符串为】:"+result); System.out.println(); Map<String,Object> htmlMap=new Html2TextUtil().getContentMap(s1); System.out.println("【原始html】:"+s1); System.out.println("【纯文本段及文本坐标】:"); List<String> list= (List<String>)htmlMap.get("textList"); for(String str:list){ System.out.println(str); } } }
运行结果截图: