在Java中輕松將HTML格式文本轉(zhuǎn)換為純文本的方法示例(保留換行)
第一步:引入Jsoup和lang和lang3的依賴:
Jsoup是HTML解析器lang和lang3這兩個(gè)包里有轉(zhuǎn)換所需的工具類
<dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.3</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.4</version></dependency>
第二步:直接使用即可:
import org.apache.commons.lang.StringEscapeUtils;import org.apache.commons.lang3.StringUtils;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.safety.Whitelist;/** * @author Piconjo */public class Html2PlainText { public static String convert(String html) { if (StringUtils.isEmpty(html)) { return ''; } Document document = Jsoup.parse(html); Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false); document.outputSettings(outputSettings); document.select('br').append('n'); document.select('p').prepend('n'); document.select('p').append('n'); String newHtml = document.html().replaceAll('n', 'n'); String plainText = Jsoup.clean(newHtml, '', Whitelist.none(), outputSettings); String result = StringEscapeUtils.unescapeHtml(plainText.trim()); return result; }}
使用測(cè)試:
到此這篇關(guān)于在Java中輕松將HTML格式文本轉(zhuǎn)換為純文本的方法示例(保留換行)的文章就介紹到這了,更多相關(guān)Java HTML轉(zhuǎn)換為純文本內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML入門的常見(jiàn)問(wèn)題(四)2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享4. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問(wèn)題5. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法6. xml中的空格之完全解說(shuō)7. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)8. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問(wèn)題……9. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法10. WMLScript的語(yǔ)法基礎(chǔ)
