java工具类mht转html格式文件 及简单的HTML解析
- package com.szy.project.utils;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.Reader;
- import java.io.Writer;
- import java.util.Enumeration;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.Session;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- /**
- * 转换工具 ---------- 需要引入第三方依赖 javaMail转换格式 和 jsoup解析HTML
- * jsoup 文档地址 :http://www.open-open.com/jsoup/parse-document-from-string.htm
- * 将mht 转化成 HTML
- * @author 隔壁老王
- *
- */
- public class Mht2HtmlUtil {
- public static void main(String[] args) throws IOException {
- /**
- * 转换
- */
- //mht2html("f:\\job_111.mht", "f:\\test.htm");
- /**
- * 获取姓名和性别
- */
- String nameAndSex = Mht2HtmlUtil.findResultValue("f:\\test.htm", "li", "info_name");
- String tmpString = nameAndSex.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");// 去掉所有中英文符号
- char[] carr = tmpString.toCharArray();
- for (int i = 0; i < tmpString.length(); i++) {
- if (carr[i] < 0xFF) {
- carr[i] = ' ';// 过滤掉非汉字内容
- }
- }
- System.out.println(tmpString.substring(0, tmpString.length()-1)); //姓名
- System.out.println(tmpString.substring(tmpString.length()-1)); //性别
- /**
- * 获取教育经历
- */
- File htmlf=new File("f:\\test.htm");
- Document doc=Jsoup.parse(htmlf, "UTF-8");
- String ss=doc.body().toString();
- //class等于masthead的li标签
- Object[] aa= doc.select("div.detaile_box").toArray();
- for (int i = 0; i < aa.length; i++) {
- if(i==3){
- String strtext = aa[i].toString();
- Document docs = Jsoup.parse(strtext);
- Object[] bb= docs.select("b.edu_main_sch").toArray();
- for (int j = 0; j < bb.length; j++) {
- String tt = bb[j].toString();
- Document doct = Jsoup.parse(tt);
- String result = doct.select("b.edu_main_sch").text();
- String a=result.substring(0, result.indexOf("|")).trim();
- String b=result.substring(result.lastIndexOf("|")+1, result.length()).trim();
- System.out.println(a+" "+b); //毕业院校加学历
- }
- }
- }
- }
- /**
- * 解析标签 获取标签值
- * @param htmlFilePath 文件路径
- * @param lableName 标签名称
- * @param onClassName 标签名称
- * @return
- * @throws IOException
- */
- public static String findResultValue(String htmlFilePath , String lableName , String onClassName) throws IOException{
- File htmlf=new File(htmlFilePath);
- Document doc=Jsoup.parse(htmlf, "UTF-8");
- String bodyText=doc.body().toString(); // 获取文件文本信息
- //class等于onClassName的lableName标签
- String resultValue = doc.select(lableName+"."+onClassName).first().text();
- return resultValue;
- }
- /**
- * 解析标签结果返回多个值
- * @param htmlFilePath 文件路径
- * @param lableName 标签名称
- * @param onClassName 标签名称
- * @return
- * @throws IOException
- */
- public static Object[] findResultValueToArray (String htmlFilePath , String lableName , String onClassName) throws IOException{
- File htmlf=new File(htmlFilePath);
- Document doc=Jsoup.parse(htmlf, "UTF-8");
- String bodyText=doc.body().toString(); // 获取文件文本信息
- return doc.select(lableName+"."+onClassName).toArray();
- }
- /**
- * 将 mht文件转换成 html文件
- *
- * @param s_SrcMht // mht 文件的位置
- * @param s_DescHtml // 转换后输出的HTML的位置
- */
- public static void mht2html(String srcMht, String descHtml) {
- try {
- InputStream fis = new FileInputStream(srcMht);
- Session mailSession = Session.getDefaultInstance(
- System.getProperties(), null);
- MimeMessage msg = new MimeMessage(mailSession, fis);
- Object content = msg.getContent();
- if (content instanceof Multipart) {
- MimeMultipart mp = (MimeMultipart) content;
- MimeBodyPart bp1 = (MimeBodyPart) mp.getBodyPart(0);
- // 获取mht文件内容代码的编码
- String strEncodng = getEncoding(bp1);
- // 获取mht文件的内容
- String strText = getHtmlText(bp1, strEncodng);
- if (strText == null)
- return;
- /**
- * 创建以mht文件名称的文件夹,主要用来保存资源文件。 这里不需要所以注释掉了
- */
- /* File parent = null;
- if (mp.getCount() > 1) {
- parent = new File(new File(descHtml).getAbsolutePath()
- + ".files");
- parent.mkdirs();
- if (!parent.exists()) { // 创建文件夹失败的话则退出
- return;
- }
- }*/
- /**
- * FOR中代码 主要是保存资源文件及替换路径 这里不需要所以注释掉了
- */
- /* for (int i = 1; i < mp.getCount(); ++i) {
- MimeBodyPart bp = (MimeBodyPart) mp.getBodyPart(i);
- // 获取资源文件的路径
- // 例(获取: http://xxx.com/abc.jpg)
- String strUrl = getResourcesUrl(bp);
- if (strUrl == null || strUrl.length() == 0)
- continue;
- DataHandler dataHandler = bp.getDataHandler();
- MimePartDataSource source = (MimePartDataSource) dataHandler
- .getDataSource();
- // 获取资源文件的绝对路径
- String FilePath = parent.getAbsolutePath() + File.separator
- + getName(strUrl, i);
- File resources = new File(FilePath);
- // 保存资源文件
- if (SaveResourcesFile(resources, bp.getInputStream())) {
- // 将远程地址替换为本地地址 如图片、JS、CSS样式等等
- strText = strText.replace(strUrl,
- resources.getAbsolutePath());
- }
- }*/
- // 最后保存HTML文件
- SaveHtml(strText, descHtml, strEncodng);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 获取mht文件内容中资源文件的名称
- *
- * @param strName
- * @param ID
- * @return
- */
- public static String getName(String strName, int ID) {
- char separator1 = '/';
- char separator2 = '\\';
- // 将换行替换
- strName = strName.replaceAll("\r\n", "");
- // 获取文件名称
- if (strName.lastIndexOf(separator1) >= 0) {
- return strName.substring(strName.lastIndexOf(separator1) + 1);
- }
- if (strName.lastIndexOf(separator2) >= 0) {
- return strName.substring(strName.lastIndexOf(separator2) + 1);
- }
- return "";
- }
- /**
- * 将提取出来的html内容写入保存的路径中。
- *
- * @param strText
- * @param strHtml
- * @param strEncodng
- */
- public static boolean SaveHtml(String s_HtmlTxt, String s_HtmlPath,
- String s_Encode) {
- try {
- Writer out = null;
- out = new OutputStreamWriter(
- new FileOutputStream(s_HtmlPath, false), s_Encode);
- out.write(s_HtmlTxt);
- out.close();
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * 保存网页中的JS、图片、CSS样式等资源文件
- *
- * @param SrcFile
- * 源文件
- * @param inputStream
- * 输入流
- * @return
- */
- private static boolean SaveResourcesFile(File SrcFile,
- InputStream inputStream) {
- if (SrcFile == null || inputStream == null) {
- return false;
- }
- BufferedInputStream in = null;
- FileOutputStream fio = null;
- BufferedOutputStream osw = null;
- try {
- in = new BufferedInputStream(inputStream);
- fio = new FileOutputStream(SrcFile);
- osw = new BufferedOutputStream(new DataOutputStream(fio));
- int index = 0;
- byte[] a = new byte[1024];
- while ((index = in.read(a)) != -1) {
- osw.write(a, 0, index);
- }
- osw.flush();
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- if (osw != null)
- osw.close();
- if (fio != null)
- fio.close();
- if (in != null)
- in.close();
- if (inputStream != null)
- inputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- }
- /**
- * 获取mht文件里资源文件的URL路径
- *
- * @param bp
- * @return
- */
- private static String getResourcesUrl(MimeBodyPart bp) {
- if (bp == null) {
- return null;
- }
- try {
- Enumeration list = bp.getAllHeaders();
- while (list.hasMoreElements()) {
- javax.mail.Header head = (javax.mail.Header) list.nextElement();
- if (head.getName().compareTo("Content-Location") == 0) {
- return head.getValue();
- }
- }
- return null;
- } catch (MessagingException e) {
- return null;
- }
- }
- /**
- * 获取mht文件中的内容代码
- *
- * @param bp
- * @param strEncoding
- * 该mht文件的编码
- * @return
- */
- private static String getHtmlText(MimeBodyPart bp, String strEncoding) {
- InputStream textStream = null;
- BufferedInputStream buff = null;
- BufferedReader br = null;
- Reader r = null;
- try {
- textStream = bp.getInputStream();
- buff = new BufferedInputStream(textStream);
- r = new InputStreamReader(buff, strEncoding);
- br = new BufferedReader(r);
- StringBuffer strHtml = new StringBuffer("");
- String strLine = null;
- while ((strLine = br.readLine()) != null) {
- System.out.println(strLine);
- strHtml.append(strLine + "\r\n");
- }
- br.close();
- r.close();
- textStream.close();
- return strHtml.toString();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (br != null)
- br.close();
- if (buff != null)
- buff.close();
- if (textStream != null)
- textStream.close();
- } catch (Exception e) {
- }
- }
- return null;
- }
- /**
- * 获取mht网页文件中内容代码的编码
- *
- * @param bp
- * @return
- */
- private static String getEncoding(MimeBodyPart bp) {
- if (bp == null) {
- return null;
- }
- try {
- Enumeration list = bp.getAllHeaders();
- while (list.hasMoreElements()) {
- javax.mail.Header head = (javax.mail.Header) list.nextElement();
- if (head.getName().equalsIgnoreCase("Content-Type")) {
- String strType = head.getValue();
- int pos = strType.indexOf("charset=");
- if (pos >= 0) {
- String strEncoding = strType.substring(pos + 8,
- strType.length());
- if (strEncoding.startsWith("\"")
- || strEncoding.startsWith("\'")) {
- strEncoding = strEncoding.substring(1,
- strEncoding.length());
- }
- if (strEncoding.endsWith("\"")
- || strEncoding.endsWith("\'")) {
- strEncoding = strEncoding.substring(0,
- strEncoding.length() - 1);
- }
- if (strEncoding.toLowerCase().compareTo("gb2312") == 0) {
- strEncoding = "gbk";
- }
- return strEncoding;
- }
- }
- }
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 删除指定文件
- * @param filePath 文件路径
- * @param fileName 文件名称
- * @param layout 文件格式
- */
- public static void deleteFileName(String filePath , String fileName , String layout){
- File folder = new File(filePath);
- String fileNameOnLayout=fileName+"."+layout;
- File[] files = folder.listFiles(); //获取该文件夹下的所有文件
- for(File file:files){
- if(file.getName().equals(fileNameOnLayout)){
- file.delete();
- }
- }
- }
- }
工具所用到的第三方依赖:
- <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4.7</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
- <dependency>
- <groupId>org.jsoup</groupId>
- <artifactId>jsoup</artifactId>
- <version>1.10.1</version>
- </dependency>
java工具类mht转html格式文件 及简单的HTML解析的更多相关文章
- java工具类(五)之日期格式字符串与日期实现互转
JAVA字符串转日期或日期转字符串 项目开发过程中需要实现日期格式的字符串与日期进行互转,并进行日期的加减操作. Demo如下: package weiming.lmapp.utils; import ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- java工具类
1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...
- Java工具类——通过配置XML验证Map
Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...
- 排名前 16 的 Java 工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 排名前16的Java工具类
原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...
- 干货:排名前16的Java工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 常用高效 Java 工具类总结
一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...
- 几种高效的Java工具类推荐
本文将介绍了十二种常用的.高效的Java工具类 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类. 在开发中,使用这些工具类,不仅可以提高编码效率,还 ...
随机推荐
- Search for a range, 在一个可能有重复元素的有序序列里找到指定元素的起始和结束位置
问题描述:给定一个有序序列,找到指定元素的起始和结束位置.例如:1234555,5,起始4结束6 算法分析:其实就是一个二分查找的利用.但是特殊就在不是找到某个元素,而是找到下标.也就是在nums[m ...
- hdu 5768 Lucky7 中国剩余定理+容斥+快速乘
Lucky7 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Problem D ...
- Spring + Spring MVC + MyBatis框架整合
---恢复内容开始--- 一.Maven Web项目创建 如有需要,请参考:使用maven创建web项目 二.Spring + Spring MVC + MyBatis整合 1.Maven引入需要的J ...
- Spark- 使用hiveContext时提交作业报错
在spark上操作hive时不需要搭建hive环境,只需要从现有的hive集群中hive的conf目录下拷贝 hive-site.xml 到spark的conf目录下即可提交程序运行 出现报错 Cau ...
- 如何在深层嵌套ngRepeat中获取不同层级的$index
<ul class="list-group" ng-repeat="item in vm.appData" ng-init="outerInde ...
- 源码安装LNMP与搭建Zabbix
系统环境:CentOS release 6.5 (Final) 搭建Zabbix 3.0对PHP环境要求>= 5.4 一.下载NMP的软件包: N:wget http://nginx.org/d ...
- Redis-sentinel哨兵模式集群方案配置
一.sentinel介绍 Redis Sentinel Sentinel(哨兵)是用于监控redis集群中Master状态的工具,其已经被集成在redis2.4+的版本中 Sentinel作用: 1) ...
- jQueryValidation插件API 学习
一般格式: $('').viladata({ rules:{ username:{ required:true, maxlength:2, minlength:10, remote:{ url:&qu ...
- wc.exe(c语言实现)
Github项目地址:https://github.com/zhongciting2009/wc WC 项目要求 wc.exe 是一个常见的工具,它能统计文本文件的字符数.单词数和行数.这个项目要求写 ...
- 【git】项目更新方法
[放弃修改] 工作区 -- 暂存区 -- 本地仓库 -- 远程仓库 工作区 -- 暂存区: git diff git checkout . / git reset --hard 暂存区 -- 本地 ...