1. package com.szy.project.utils;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.BufferedReader;
  6. import java.io.DataOutputStream;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13. import java.io.OutputStreamWriter;
  14. import java.io.Reader;
  15. import java.io.Writer;
  16. import java.util.Enumeration;
  17. import javax.mail.MessagingException;
  18. import javax.mail.Multipart;
  19. import javax.mail.Session;
  20. import javax.mail.internet.MimeBodyPart;
  21. import javax.mail.internet.MimeMessage;
  22. import javax.mail.internet.MimeMultipart;
  23. import org.jsoup.Jsoup;
  24. import org.jsoup.nodes.Document;
  25.  
  26. /**
  27. * 转换工具 ---------- 需要引入第三方依赖 javaMail转换格式 和 jsoup解析HTML
  28. * jsoup 文档地址 :http://www.open-open.com/jsoup/parse-document-from-string.htm
  29. * 将mht 转化成 HTML
  30. * @author 隔壁老王
  31. *
  32. */
  33. public class Mht2HtmlUtil {
  34.  
  35. public static void main(String[] args) throws IOException {
  36. /**
  37. * 转换
  38. */
  39. //mht2html("f:\\job_111.mht", "f:\\test.htm");
  40.  
  41. /**
  42. * 获取姓名和性别
  43. */
  44. String nameAndSex = Mht2HtmlUtil.findResultValue("f:\\test.htm", "li", "info_name");
  45.  
  46. String tmpString = nameAndSex.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");// 去掉所有中英文符号
  47. char[] carr = tmpString.toCharArray();
  48. for (int i = 0; i < tmpString.length(); i++) {
  49. if (carr[i] < 0xFF) {
  50. carr[i] = ' ';// 过滤掉非汉字内容
  51. }
  52. }
  53. System.out.println(tmpString.substring(0, tmpString.length()-1)); //姓名
  54. System.out.println(tmpString.substring(tmpString.length()-1)); //性别
  55.  
  56. /**
  57. * 获取教育经历
  58. */
  59. File htmlf=new File("f:\\test.htm");
  60. Document doc=Jsoup.parse(htmlf, "UTF-8");
  61. String ss=doc.body().toString();
  62. //class等于masthead的li标签
  63. Object[] aa= doc.select("div.detaile_box").toArray();
  64. for (int i = 0; i < aa.length; i++) {
  65. if(i==3){
  66. String strtext = aa[i].toString();
  67. Document docs = Jsoup.parse(strtext);
  68. Object[] bb= docs.select("b.edu_main_sch").toArray();
  69. for (int j = 0; j < bb.length; j++) {
  70. String tt = bb[j].toString();
  71. Document doct = Jsoup.parse(tt);
  72. String result = doct.select("b.edu_main_sch").text();
  73. String a=result.substring(0, result.indexOf("|")).trim();
  74. String b=result.substring(result.lastIndexOf("|")+1, result.length()).trim();
  75. System.out.println(a+" "+b); //毕业院校加学历
  76.  
  77. }
  78. }
  79.  
  80. }
  81.  
  82. }
  83.  
  84. /**
  85. * 解析标签 获取标签值
  86. * @param htmlFilePath 文件路径
  87. * @param lableName 标签名称
  88. * @param onClassName 标签名称
  89. * @return
  90. * @throws IOException
  91. */
  92. public static String findResultValue(String htmlFilePath , String lableName , String onClassName) throws IOException{
  93. File htmlf=new File(htmlFilePath);
  94. Document doc=Jsoup.parse(htmlf, "UTF-8");
  95. String bodyText=doc.body().toString(); // 获取文件文本信息
  96. //class等于onClassName的lableName标签
  97. String resultValue = doc.select(lableName+"."+onClassName).first().text();
  98.  
  99. return resultValue;
  100. }
  101.  
  102. /**
  103. * 解析标签结果返回多个值
  104. * @param htmlFilePath 文件路径
  105. * @param lableName 标签名称
  106. * @param onClassName 标签名称
  107. * @return
  108. * @throws IOException
  109. */
  110. public static Object[] findResultValueToArray (String htmlFilePath , String lableName , String onClassName) throws IOException{
  111. File htmlf=new File(htmlFilePath);
  112. Document doc=Jsoup.parse(htmlf, "UTF-8");
  113. String bodyText=doc.body().toString(); // 获取文件文本信息
  114. return doc.select(lableName+"."+onClassName).toArray();
  115. }
  116.  
  117. /**
  118. * 将 mht文件转换成 html文件
  119. *
  120. * @param s_SrcMht // mht 文件的位置
  121. * @param s_DescHtml // 转换后输出的HTML的位置
  122. */
  123. public static void mht2html(String srcMht, String descHtml) {
  124. try {
  125. InputStream fis = new FileInputStream(srcMht);
  126. Session mailSession = Session.getDefaultInstance(
  127. System.getProperties(), null);
  128. MimeMessage msg = new MimeMessage(mailSession, fis);
  129. Object content = msg.getContent();
  130. if (content instanceof Multipart) {
  131. MimeMultipart mp = (MimeMultipart) content;
  132. MimeBodyPart bp1 = (MimeBodyPart) mp.getBodyPart(0);
  133.  
  134. // 获取mht文件内容代码的编码
  135. String strEncodng = getEncoding(bp1);
  136.  
  137. // 获取mht文件的内容
  138. String strText = getHtmlText(bp1, strEncodng);
  139. if (strText == null)
  140. return;
  141.  
  142. /**
  143. * 创建以mht文件名称的文件夹,主要用来保存资源文件。 这里不需要所以注释掉了
  144. */
  145. /* File parent = null;
  146. if (mp.getCount() > 1) {
  147. parent = new File(new File(descHtml).getAbsolutePath()
  148. + ".files");
  149. parent.mkdirs();
  150. if (!parent.exists()) { // 创建文件夹失败的话则退出
  151. return;
  152. }
  153. }*/
  154.  
  155. /**
  156. * FOR中代码 主要是保存资源文件及替换路径 这里不需要所以注释掉了
  157. */
  158. /* for (int i = 1; i < mp.getCount(); ++i) {
  159. MimeBodyPart bp = (MimeBodyPart) mp.getBodyPart(i);
  160. // 获取资源文件的路径
  161. // 例(获取: http://xxx.com/abc.jpg)
  162. String strUrl = getResourcesUrl(bp);
  163. if (strUrl == null || strUrl.length() == 0)
  164. continue;
  165.  
  166. DataHandler dataHandler = bp.getDataHandler();
  167. MimePartDataSource source = (MimePartDataSource) dataHandler
  168. .getDataSource();
  169.  
  170. // 获取资源文件的绝对路径
  171. String FilePath = parent.getAbsolutePath() + File.separator
  172. + getName(strUrl, i);
  173. File resources = new File(FilePath);
  174.  
  175. // 保存资源文件
  176. if (SaveResourcesFile(resources, bp.getInputStream())) {
  177. // 将远程地址替换为本地地址 如图片、JS、CSS样式等等
  178. strText = strText.replace(strUrl,
  179. resources.getAbsolutePath());
  180. }
  181. }*/
  182.  
  183. // 最后保存HTML文件
  184. SaveHtml(strText, descHtml, strEncodng);
  185. }
  186. } catch (Exception e) {
  187. e.printStackTrace();
  188. }
  189. }
  190.  
  191. /**
  192. * 获取mht文件内容中资源文件的名称
  193. *
  194. * @param strName
  195. * @param ID
  196. * @return
  197. */
  198. public static String getName(String strName, int ID) {
  199. char separator1 = '/';
  200. char separator2 = '\\';
  201. // 将换行替换
  202. strName = strName.replaceAll("\r\n", "");
  203.  
  204. // 获取文件名称
  205. if (strName.lastIndexOf(separator1) >= 0) {
  206. return strName.substring(strName.lastIndexOf(separator1) + 1);
  207. }
  208. if (strName.lastIndexOf(separator2) >= 0) {
  209. return strName.substring(strName.lastIndexOf(separator2) + 1);
  210. }
  211. return "";
  212. }
  213.  
  214. /**
  215. * 将提取出来的html内容写入保存的路径中。
  216. *
  217. * @param strText
  218. * @param strHtml
  219. * @param strEncodng
  220. */
  221. public static boolean SaveHtml(String s_HtmlTxt, String s_HtmlPath,
  222. String s_Encode) {
  223. try {
  224. Writer out = null;
  225. out = new OutputStreamWriter(
  226. new FileOutputStream(s_HtmlPath, false), s_Encode);
  227. out.write(s_HtmlTxt);
  228. out.close();
  229. } catch (Exception e) {
  230. return false;
  231. }
  232. return true;
  233. }
  234.  
  235. /**
  236. * 保存网页中的JS、图片、CSS样式等资源文件
  237. *
  238. * @param SrcFile
  239. * 源文件
  240. * @param inputStream
  241. * 输入流
  242. * @return
  243. */
  244. private static boolean SaveResourcesFile(File SrcFile,
  245. InputStream inputStream) {
  246. if (SrcFile == null || inputStream == null) {
  247. return false;
  248. }
  249.  
  250. BufferedInputStream in = null;
  251. FileOutputStream fio = null;
  252. BufferedOutputStream osw = null;
  253. try {
  254. in = new BufferedInputStream(inputStream);
  255. fio = new FileOutputStream(SrcFile);
  256. osw = new BufferedOutputStream(new DataOutputStream(fio));
  257. int index = 0;
  258. byte[] a = new byte[1024];
  259. while ((index = in.read(a)) != -1) {
  260. osw.write(a, 0, index);
  261. }
  262. osw.flush();
  263. return true;
  264. } catch (Exception e) {
  265. e.printStackTrace();
  266. return false;
  267. } finally {
  268. try {
  269. if (osw != null)
  270. osw.close();
  271. if (fio != null)
  272. fio.close();
  273. if (in != null)
  274. in.close();
  275. if (inputStream != null)
  276. inputStream.close();
  277. } catch (Exception e) {
  278. e.printStackTrace();
  279. return false;
  280. }
  281. }
  282. }
  283.  
  284. /**
  285. * 获取mht文件里资源文件的URL路径
  286. *
  287. * @param bp
  288. * @return
  289. */
  290. private static String getResourcesUrl(MimeBodyPart bp) {
  291. if (bp == null) {
  292. return null;
  293. }
  294. try {
  295. Enumeration list = bp.getAllHeaders();
  296. while (list.hasMoreElements()) {
  297. javax.mail.Header head = (javax.mail.Header) list.nextElement();
  298. if (head.getName().compareTo("Content-Location") == 0) {
  299. return head.getValue();
  300. }
  301. }
  302. return null;
  303. } catch (MessagingException e) {
  304. return null;
  305. }
  306. }
  307.  
  308. /**
  309. * 获取mht文件中的内容代码
  310. *
  311. * @param bp
  312. * @param strEncoding
  313. * 该mht文件的编码
  314. * @return
  315. */
  316. private static String getHtmlText(MimeBodyPart bp, String strEncoding) {
  317. InputStream textStream = null;
  318. BufferedInputStream buff = null;
  319. BufferedReader br = null;
  320. Reader r = null;
  321. try {
  322. textStream = bp.getInputStream();
  323. buff = new BufferedInputStream(textStream);
  324. r = new InputStreamReader(buff, strEncoding);
  325. br = new BufferedReader(r);
  326. StringBuffer strHtml = new StringBuffer("");
  327. String strLine = null;
  328. while ((strLine = br.readLine()) != null) {
  329. System.out.println(strLine);
  330. strHtml.append(strLine + "\r\n");
  331. }
  332. br.close();
  333. r.close();
  334. textStream.close();
  335. return strHtml.toString();
  336. } catch (Exception e) {
  337. e.printStackTrace();
  338. } finally {
  339. try {
  340. if (br != null)
  341. br.close();
  342. if (buff != null)
  343. buff.close();
  344. if (textStream != null)
  345. textStream.close();
  346. } catch (Exception e) {
  347. }
  348. }
  349. return null;
  350. }
  351.  
  352. /**
  353. * 获取mht网页文件中内容代码的编码
  354. *
  355. * @param bp
  356. * @return
  357. */
  358. private static String getEncoding(MimeBodyPart bp) {
  359. if (bp == null) {
  360. return null;
  361. }
  362. try {
  363. Enumeration list = bp.getAllHeaders();
  364. while (list.hasMoreElements()) {
  365. javax.mail.Header head = (javax.mail.Header) list.nextElement();
  366. if (head.getName().equalsIgnoreCase("Content-Type")) {
  367. String strType = head.getValue();
  368. int pos = strType.indexOf("charset=");
  369. if (pos >= 0) {
  370. String strEncoding = strType.substring(pos + 8,
  371. strType.length());
  372. if (strEncoding.startsWith("\"")
  373. || strEncoding.startsWith("\'")) {
  374. strEncoding = strEncoding.substring(1,
  375. strEncoding.length());
  376. }
  377. if (strEncoding.endsWith("\"")
  378. || strEncoding.endsWith("\'")) {
  379. strEncoding = strEncoding.substring(0,
  380. strEncoding.length() - 1);
  381. }
  382. if (strEncoding.toLowerCase().compareTo("gb2312") == 0) {
  383. strEncoding = "gbk";
  384. }
  385. return strEncoding;
  386. }
  387. }
  388. }
  389. } catch (MessagingException e) {
  390. e.printStackTrace();
  391. }
  392. return null;
  393. }
  394.  
  395. /**
  396. * 删除指定文件
  397. * @param filePath 文件路径
  398. * @param fileName 文件名称
  399. * @param layout 文件格式
  400. */
  401. public static void deleteFileName(String filePath , String fileName , String layout){
  402.  
  403. File folder = new File(filePath);
  404. String fileNameOnLayout=fileName+"."+layout;
  405. File[] files = folder.listFiles(); //获取该文件夹下的所有文件
  406. for(File file:files){
  407. if(file.getName().equals(fileNameOnLayout)){
  408. file.delete();
  409. }
  410. }
  411.  
  412. }
  413.  
  414. }

工具所用到的第三方依赖:

  1. <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
  2. <dependency>
  3. <groupId>javax.mail</groupId>
  4. <artifactId>mail</artifactId>
  5. <version>1.4.7</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
  8. <dependency>
  9. <groupId>org.jsoup</groupId>
  10. <artifactId>jsoup</artifactId>
  11. <version>1.10.1</version>
  12. </dependency>

java工具类mht转html格式文件 及简单的HTML解析的更多相关文章

  1. java工具类(五)之日期格式字符串与日期实现互转

    JAVA字符串转日期或日期转字符串 项目开发过程中需要实现日期格式的字符串与日期进行互转,并进行日期的加减操作. Demo如下: package weiming.lmapp.utils; import ...

  2. java http工具类和HttpUrlConnection上传文件分析

    利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...

  3. java工具类

    1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...

  4. Java工具类——通过配置XML验证Map

    Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...

  5. 排名前 16 的 Java 工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  6. 排名前16的Java工具类

    原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...

  7. 干货:排名前16的Java工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  8. 常用高效 Java 工具类总结

    一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...

  9. 几种高效的Java工具类推荐

    本文将介绍了十二种常用的.高效的Java工具类 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类. 在开发中,使用这些工具类,不仅可以提高编码效率,还 ...

随机推荐

  1. Search for a range, 在一个可能有重复元素的有序序列里找到指定元素的起始和结束位置

    问题描述:给定一个有序序列,找到指定元素的起始和结束位置.例如:1234555,5,起始4结束6 算法分析:其实就是一个二分查找的利用.但是特殊就在不是找到某个元素,而是找到下标.也就是在nums[m ...

  2. hdu 5768 Lucky7 中国剩余定理+容斥+快速乘

    Lucky7 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Problem D ...

  3. Spring + Spring MVC + MyBatis框架整合

    ---恢复内容开始--- 一.Maven Web项目创建 如有需要,请参考:使用maven创建web项目 二.Spring + Spring MVC + MyBatis整合 1.Maven引入需要的J ...

  4. Spark- 使用hiveContext时提交作业报错

    在spark上操作hive时不需要搭建hive环境,只需要从现有的hive集群中hive的conf目录下拷贝 hive-site.xml 到spark的conf目录下即可提交程序运行 出现报错 Cau ...

  5. 如何在深层嵌套ngRepeat中获取不同层级的$index

    <ul class="list-group" ng-repeat="item in vm.appData" ng-init="outerInde ...

  6. 源码安装LNMP与搭建Zabbix

    系统环境:CentOS release 6.5 (Final) 搭建Zabbix 3.0对PHP环境要求>= 5.4 一.下载NMP的软件包: N:wget http://nginx.org/d ...

  7. Redis-sentinel哨兵模式集群方案配置

    一.sentinel介绍 Redis Sentinel Sentinel(哨兵)是用于监控redis集群中Master状态的工具,其已经被集成在redis2.4+的版本中 Sentinel作用: 1) ...

  8. jQueryValidation插件API 学习

    一般格式: $('').viladata({ rules:{ username:{ required:true, maxlength:2, minlength:10, remote:{ url:&qu ...

  9. wc.exe(c语言实现)

    Github项目地址:https://github.com/zhongciting2009/wc WC 项目要求 wc.exe 是一个常见的工具,它能统计文本文件的字符数.单词数和行数.这个项目要求写 ...

  10. 【git】项目更新方法

    [放弃修改] 工作区 -- 暂存区 -- 本地仓库 -- 远程仓库 工作区 -- 暂存区: git diff git checkout .  /  git reset --hard 暂存区 -- 本地 ...