Html编码格式读取,获取纯文本
maven引入获取编码的jar
<dependency><groupId>com.ibm.icu</groupId><artifactId>icu4j</artifactId><version>67.1</version></dependency>
获取文件编码
package com.lovnx.note.util;import com.ibm.icu.text.CharsetDetector;import com.ibm.icu.text.CharsetMatch;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.select.Elements;import java.io.IOException;import java.net.URL;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;/*** @author https://github.com/TianPuJun @256g的胃* @ClassName HtmlParse* @Description* @Date 15:32 2020/7/9**/public class HtmlParse {public static String getEncode(String filePath) throws IOException {Path path = Paths.get(filePath);byte[] data = Files.readAllBytes(path);CharsetDetector detector = new CharsetDetector();detector.setText(data);CharsetMatch match = detector.detect();String encoding = match.getName();System.out.println("The Content in " + match.getName());return encoding;}public static void main(String[] args) throws Exception {System.out.println(HtmlParse.getEncode("/Users/cxt/Downloads/test.html"));}}
上面获取文件编码是为了在服务器根据文件流下载文件时防止文件乱码直接指定编码格式,然后再根据下载下来的文件识别纯文本
Document doc = Jsoup.parse("读取的文本字符串,此处应该是带html标签的");String text = doc.text();
jsoup也支持 直接指定文件的形式去获取纯文本
参考 https://jsoup.org/
