mht文件转为html文件

由于之前提供的方式一,可能在工程的众多依赖中,存在jar包冲突,如mail.jar和javaee5.jar都存在javax.mail的类路径,导致在强制类型转换会出现异常,解决方式略显蛋疼(如去掉其中一个jar中的javax.mail的包),所以我们寻找到另一种解析方式,而且个人感觉比方式一会简单点:

  • maven项目-pom依赖
  • 解析mht文件代码

maven项目-pom依赖

MIME4J解析包 apache-mime4j

<dependency><groupId>org.apache.james</groupId><artifactId>apache-mime4j-core</artifactId><version>0.7.2</version>
</dependency>
<dependency><groupId>org.apache.james</groupId><artifactId>apache-mime4j-dom</artifactId><version>0.7.2</version>
</dependency>

解析mht文件代码

解析 mht文件 转为html,以及相关的js、css等资源文件

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.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;import org.apache.james.mime4j.dom.BinaryBody;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Header;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.dom.TextBody;
import org.apache.james.mime4j.message.DefaultMessageBuilder;
import org.apache.james.mime4j.stream.Field;public class Mime4jUtil {public static void main(String[] args) {//MessageTree.main(new String[]{"E:\\webdb\\mystruts\\src\\main\\webapp\\mhtfile\\123,123.mht"});mht2Html("E:\\webdb\\mystruts\\src\\main\\webapp\\mhtfile\\123,123.mht", "E:\\webdb\\mystruts\\src\\main\\webapp\\mhtfile\\123,123.htm", "");}public static void mht2Html(String srcMht, String targetFile, String serverPath){DefaultMessageBuilder builder = new DefaultMessageBuilder();try {InputStream inputStream = new FileInputStream(new File(srcMht));Message message = builder.parseMessage(inputStream);Multipart multipart = (Multipart) message.getBody();List<Entity> parts = multipart.getBodyParts();//1.取主体StringBuilder htmlTextStr = new StringBuilder();String encoding = null;for (Entity entity : parts) {if(!"text/html".equals(entity.getMimeType())){continue;}//取编码encoding = getEncoding(entity);TextBody body = (TextBody)entity.getBody();BufferedReader br = new BufferedReader(body.getReader());String line = null;while((line = br.readLine()) != null){htmlTextStr.append(line);}break;}String htmlText = htmlTextStr.toString();//2.取资源文件 //创建以mht文件名称的文件夹,主要用来保存资源文件。 File resourceFile = null; if (parts.size() > 1) {String sourcePath = targetFile.substring(0, targetFile.lastIndexOf(".")) + ".files";resourceFile = new File(sourcePath);if(!resourceFile.exists()){resourceFile.mkdirs();}}for (Entity entity : parts) {if("text/html".equals(entity.getMimeType())){continue;}String strUrl = getResourcesUrl(entity);if (strUrl == null || strUrl.length() == 0)continue;// 获取资源文件的绝对路径String filePath = resourceFile.getAbsolutePath() + File.separator + getName(strUrl);File resources = new File(filePath);// 保存资源文件BinaryBody body = (BinaryBody)entity.getBody();if (saveResourcesFile(resources, body.getInputStream())) {// 将远程地址替换为本地地址 如图片、JS、CSS样式等等String replacePath = strUrl;if(strUrl.startsWith("file://")){replacePath = getRelativePath(strUrl);}String relativePath = getRelativePath(filePath);htmlText = htmlText.replaceAll(replacePath, serverPath + relativePath);}}//保存文件saveHtml(htmlText, targetFile, encoding);} catch (Exception e) {e.printStackTrace();}}/*** 获取mht文件里资源文件的URL路径* * @param bp* @return*/private static String getResourcesUrl(Entity entity) {Header header = entity.getHeader();Field field = header.getField("Content-Location");if(field == null){return null;}return field.getBody();}/*** 取文件名称* * @param strUrl* @return*/private static String getName(String strUrl){char separator = '/';if (strUrl.lastIndexOf(separator) < 0) {separator = '\\';}if(strUrl.lastIndexOf(separator) < 0){return null;}String filename = strUrl.substring(strUrl.lastIndexOf(separator) + 1);if(filename.indexOf("?") > 0){return filename.substring(0, filename.indexOf("?"));}return filename;}/*** 保存网页中的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;}}}/*** 取相对路径* @param filePath* @return*/public static String getRelativePath(String filePath) {char separator = '/';if (filePath.lastIndexOf(separator) < 0) {separator = '\\';}if(filePath.lastIndexOf(separator) < 0){return "";}String partStr = filePath.substring(0, filePath.lastIndexOf(separator));partStr = partStr.substring(0, partStr.lastIndexOf(separator));return filePath.substring(partStr.length() + 1);}/*** 将提取出来的html内容写入保存的路径中。* * @param htmlTxt* @param htmlPath* @param encoding*/public static boolean saveHtml(String htmlTxt, String htmlPath, String encoding) {//若不存在父目录,则创建File htmlFile = new File(htmlPath);if(!htmlFile.getParentFile().exists()){htmlFile.getParentFile().mkdirs();}try {Writer out = null;out = new OutputStreamWriter(new FileOutputStream(htmlPath, false), encoding);out.write(htmlTxt);out.close();} catch (Exception e) {return false;}return true;}/*** 获取mht网页文件中内容代码的编码* * @param entity* @return*/private static String getEncoding(Entity entity) {return entity.getCharset();}
}

此方法原创哦!=.=!

mht文件转为html文件(mime4j方式)相关推荐

  1. mht文件转为html文件(javax.mail方式)

    mht文件转为html文件 由于mht文件是IE特有的格式,只能IE浏览器打开.用别的浏览器,如chrome打开该类型文件会产生乱码,但是我们大部分使用的还是chrome,因此想要打开该类型的文件,其 ...

  2. tif文件转为shp文件_从Tif文件转为shp文件(ArcMap,代码)、gdal打包问题

    从Tif文件转为shp文件(ArcMap,代码) 利用ArcMap来进行转换,以预测出来的滨海湿地图像为例 第一步:打开ArcMap中的栅格转面工具 ArcMap中的栅格转面工具 点击栅格转面之后,选 ...

  3. 点云处理过程中.stl文件转为.ply文件

    点云处理过程中文件的转换问题 .stl文件转为.ply文件 .stl文件转为.ply文件 在进行点云的处理过程中需要进行文件的转换,可以使用open3d软件包进行转换,由于.ply文件有两种储存方法, ...

  4. python转csv_python脚本如何将Excel文件转为csv文件(代码)

    本篇文章给大家带来的内容是关于python脚本如何将Excel文件转为csv文件(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助.#!/usr/bin/env python __ ...

  5. 【windwos bat】批量把windows下的wav文件转为raw文件

    借助工具sox,可以批量将wav文件转为raw文件. @echo off set work_path=recordings set raw_path=raw SET mypath=%~dp0mkdir ...

  6. GDCM:png文件转为dcm文件的测试程序

    GDCM:png文件转为dcm文件的测试程序 GDCM:png文件转为dcm文件的测试程序 GDCM:png文件转为dcm文件的测试程序 #include "gdcmImageReader. ...

  7. python csv转excel_将Excel文件转为csv文件的python脚本

    将Excel文件转为csv文件的python脚本 #!/usr/bin/env python __author__ = "lrtao2010" ''' Excel文件转csv文件脚 ...

  8. Python将txt文件转为json文件

    python将txt文件转为json文件 txt文件中内容: [*]www.xiaoyang.1 [*]www.xiaoyang.12 [*]www.xiaoyang.135 [*]www.xiaoy ...

  9. matlab p文件转码 matlab pcode文件 将matlab中的p文件转为m文件工具

    matlab p文件转码 matlab pcode文件 将matlab中的p文件转为m文件工具 源码可见,解密P ID:22600679158222577美丽小飞侠大队

最新文章

  1. 安装oracle 11gR2单实例+ASM
  2. php万年历月份处理_php实现万年历的完整代码
  3. Hadoop MapReduce执行过程(一)
  4. WPF调用OCX控件
  5. OpenCV 教程入门篇
  6. 华为防火墙配置(L2TP)
  7. 计算机一级插入页眉,计算机一级考试,设置页眉为“汉字的交换码”
  8. PHP幸运抽奖系统带后台源码
  9. python duplicated函数_16、pandas的duplicated和drop_duplicaates函数
  10. 区块链+公链+区块浏览器+钱包APP
  11. stream流按照个数分割list
  12. studio 3t注册码脚本
  13. 智能微型断路器集计量,保护,控制于一体让用电更安全更智能-安科瑞 汤婉茹/孟强荣
  14. 一款json查询操作神器
  15. 摄像头工作原理及结构介绍(一)
  16. Nachos系统简介
  17. iOS 视频播放从零开始(二)
  18. AC自动机 从入门到模板
  19. Error Message:网络连接错误,详细信息:Connection pool shut down
  20. sniffer(Wireshark)抓包

热门文章

  1. php热血江湖怎么安装,端游【热血江湖】V2.0商业服务端百宝阁 GM工具+客户端+架设教程...
  2. 生动的SDN基础内容介绍(五)--SDN北向协议/接口和意图驱动
  3. html用户充值页面充值中心,好看的amazeui用户充值界面代码
  4. 计算机网络 配置 DHCP 中继的时候的几个问题
  5. WORD2010设置正文页码(不包括目录和封皮)
  6. 搭建mongo集群,以及分片和副本
  7. 怎样修改日立uax规格表_UAX型电梯调试手册.pdf
  8. 使用python在实现图片(包括扫描件的图片类pdf)转换成word文档过程中的常见问题
  9. 32位系统上开发的Access为数据库的程序在64位机器上运行出错的解决办法
  10. 螺杆机过热保护php,螺杆式空压机出现过热现象的三大因素