在Java中輕松將HTML格式文本轉(zhuǎn)換為純文本的方法示例(保留換行)
第一步:引入Jsoup和lang和lang3的依賴:
Jsoup是HTML解析器
lang和lang3這兩個包里有轉(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; } }
使用測試:
到此這篇關(guān)于在Java中輕松將HTML格式文本轉(zhuǎn)換為純文本的方法示例(保留換行)的文章就介紹到這了,更多相關(guān)Java HTML轉(zhuǎn)換為純文本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)文件夾上傳功能實(shí)例代碼(SpringBoot框架)
在web項目中上傳文件夾現(xiàn)在已經(jīng)成為了一個主流的需求,下面這篇文章主要給大家介紹了關(guān)于java實(shí)現(xiàn)文件夾上傳功能(springBoot框架)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04springboot實(shí)現(xiàn)分頁功能的完整代碼
Spring Boot是一個快速開發(fā)框架,它提供了很多便捷的功能,其中包括分頁查詢,下面這篇文章主要給大家介紹了關(guān)于springboot實(shí)現(xiàn)分頁功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04使用nacos實(shí)現(xiàn)自定義文本配置的實(shí)時刷新
我們都知道,使用Nacos時,如果將Bean使用@RefreshScope標(biāo)注之后,這個Bean中的配置就會做到實(shí)時刷新,本文給大家介紹了如何使用nacos實(shí)現(xiàn)自定義文本配置的實(shí)時刷新,需要的朋友可以參考下2024-05-05springboot利用redis、Redisson處理并發(fā)問題的操作
這篇文章主要介紹了springboot利用redis、Redisson處理并發(fā)問題的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06為什么程序中突然多了 200 個 Dubbo-thread 線程的說明
這篇文章主要介紹了為什么程序中突然多了 200 個 Dubbo-thread 線程的說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09