Java解压上传zip或rar文件,并解压遍历文件中的html的路径
1.本文只提供了一个功能的代码
public String addFreeMarker() throws Exception {
HttpSession session = request.getSession();
User user = (User) session.getAttribute(Constant.USER_SESSION_KEY);
String realName = user.getRealName();
System.out.println("--------获取登录用户信息:------------"+realName);
/* 截取后缀名 */
if (StringUtil.isEmpty(fileName)) {
throw new Exception("文件不能为空");
}
int pos = fileName.lastIndexOf(".");
String str = fileName.substring(pos+1).toLowerCase();
//判断上传文件必须是zip或者是rar否则不允许上传
if (StringUtil.isEmpty(str)||(!str.equals("zip")&&!str.equals("rar")&&!str.equals("png")&&!str.equals("jpg")&&!str.equals("gif"))) {
throw new Exception("上传文件格式错误,请重新上传");
}
// 时间加后缀名保存
saveName = new Date().getTime() + "."+str;
//文件名
saveFileName = saveName.substring(0, saveName.lastIndexOf("."));
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("upload")
+ "/" +saveFileName+"/"+ saveName);
File descFile = new File(ServletActionContext.getServletContext().getRealPath("upload")+"/"+saveFileName);
if (!descFile.exists()) {
descFile.mkdirs();
}
//解压目的文件
String descDir = ServletActionContext.getServletContext().getRealPath("upload")+"/"+saveFileName+"/";
copy(myFile, imageFile);
//自己生成主键
Long seqNo = freemarkerService.getOrderNumberSeq();
String orderNumber = RandomIdGenerator.generatorOrderNumber(seqNo);
HttpServletRequest httpRequest=(HttpServletRequest)request;
String httpURL = "http://" + request.getServerName() //服务器地址
+ ":"
+ request.getServerPort() //端口号
+ httpRequest.getContextPath(); //项目名称
String URL = httpURL+"/"+"upload"+"/"+saveFileName+"/"+saveName;
System.out.println("============访问地址是:============="+ URL);
//获取用户信息
freemarker.setFilesId(orderNumber);
freemarker.setAuthor(realName);
freemarker.setFilesName(saveFileName);
freemarker.setFilesUrl(URL);
//开始解压zip
if (str.equals("zip")) {
CompressFileUits.unZipFiles(imageFile, descDir);
//文件解压成功后,把数据插入到数据库
freemarkerService.save(freemarker);
}else if (str.equals("rar")) {
//开始解压rar
CompressFileUits.unRarFile(imageFile.getAbsolutePath(), descDir);
freemarkerService.save(freemarker);
} else if (str.equals("jpg") || str.equals("png") || str.equals("gif")) {
/**
* 增家java创建html功能,根据指定模板创建html
*/
freemarkerService.save(freemarker);
//上传的如果是图片的话,就生成html
String disrPath = ServletActionContext.getServletContext().getRealPath("template");
String sourcedir = disrPath+"/template.html";
//文件的http的路径
String IMAGEURL = httpURL+"/"+"template"+"/"+saveFileName+".html";
//saveFileName 是文件的上传的文件名称
CreateHtmlUtils.MakeHtml(sourcedir, URL, disrPath, saveFileName);
freemarkerDetailService.insertFreeMarkerDetailFile(orderNumber,saveFileName+".html",IMAGEURL,new Date());
} else {
throw new Exception("文件格式不正确不能解压");
}
//遍历文件夹
getFileList(descDir,orderNumber);
return SUCCESS;
}
2.然后是文件解压的两个类
package com.tydic.eshop.util; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile; import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader; public class CompressFileUits {
/**
* 解压到指定目录
* @param zipPath
* @param descDir
* @author*/
public static void unZipFiles(String zipPath,String descDir)throws IOException{
unZipFiles(new File(zipPath), descDir);
}
/**
* 解压文件到指定目录
* @param zipFile
* @param descDir
* @author isea533
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile,String descDir)throws IOException{
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile);
for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//输出文件路径信息
System.out.println(outPath); OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
} /**
* 根据原始rar路径,解压到指定文件夹下.
* @param srcRarPath 原始rar路径
* @param dstDirectoryPath 解压到的文件夹
*/
public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
System.out.println("非rar文件!");
return;
}
File dstDiretory = new File(dstDirectoryPath);
if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
dstDiretory.mkdirs();
}
Archive a = null;
try {
a = new Archive(new File(srcRarPath));
if (a != null) {
a.getMainHeader().print(); // 打印文件信息.
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (fh.isDirectory()) { // 文件夹
File fol = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString());
fol.mkdirs();
} else { // 文件
File out = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString().trim());
//System.out.println(out.getAbsolutePath());
try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
if (!out.exists()) {
if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
fh = a.nextFileHeader();
}
a.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.常见html的工具类,上篇文章有介绍 CreateHtmlUtils
package com.tydic.eshop.util; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar; /**
* @ClassName: CreateHtmlUtils
* @Description: Java 根据模板创建 html
* @author
* @date 2016年4月22日 下午3:51:16
*/
public class CreateHtmlUtils { public static void main(String[] args) {
String filePath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\template.html";
String imagePath ="http://localhost:8080/ecp/upload/1461293787628/1461293787628.jpg";
String disrPath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\";
String fileName = "liuren";
MakeHtml(filePath,imagePath,disrPath,fileName);
}
/**
* @Title: MakeHtml
* @Description: 创建html
* @param filePath 设定模板文件
* @param imagePath 需要显示图片的路径
* @param disrPath 生成html的存放路径
* @param fileName 生成html名字
* @return void 返回类型
* @throws
*/
public static void MakeHtml(String filePath,String imagePath,String disrPath,String fileName ){
try {
String title = "<image src="+'"'+imagePath+'"'+"/>";
System.out.print(filePath);
String templateContent = "";
FileInputStream fileinputstream = new FileInputStream(filePath);// 读取模板文件
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
System.out.print(templateContent);
templateContent = templateContent.replaceAll("###title###", title);
System.out.print(templateContent); String fileame = fileName + ".html";
fileame = disrPath+"/" + fileame;// 生成的html文件保存路径。
FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
System.out.print("文件输出路径:");
System.out.print(fileame);
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
} catch (Exception e) {
System.out.print(e.toString());
}
} }
4.复制的方法 copy
// 复制方法
public static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
5.便利解压的的zip或者是rar文件夹
/**
* @throws ServiceException
* @Title: getFileList
* @Description: 递归遍历指定文件夹下的文件
* @param @param strPath
* @param @return 设定文件
* @return List<File> 返回类型
* @throws
*/
public List<File> getFileList(String strPath,String fileordernumber) throws ServiceException {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
List<File> fileList = new ArrayList<File>();
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判断是文件还是文件夹
getFileList(files[i].getAbsolutePath(),fileordernumber); // 获取文件绝对路径
System.out.println("输出文件的绝对路径"+files[i].getAbsolutePath());
} else if (fileName.endsWith("html")) { // 判断文件名是否以.avi结尾
String strFileName = files[i].getAbsolutePath();
System.out.println("------------" + strFileName+"+++++"+fileName);
// uploadcompressDetailService.insertCompressDetailFile(fileordernumber,fileName,strFileName,new Date());
freemarkerDetailService.insertFreeMarkerDetailFile(fileordernumber,fileName,strFileName,new Date());
fileList.add(files[i]);
} else {
continue;
}
} }
return fileList;
}
6.其中需要的架包
<!-- 导入zip解压包 -->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<!-- 导入rar解压包 -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
Java解压上传zip或rar文件,并解压遍历文件中的html的路径的更多相关文章
- PHP自动解压上传的rar文件
PHP自动解压上传的rar文件 浏览:383 发布日期:2015/07/20 分类:功能实现 关键字: php函数 php扩展 大家都知道php有个zip类可直接操作zip压缩文件,可是用户有时候 ...
- php上传zip文件在线解压文件在指定目录下,CI框架版本
我从网上找的文件php在线解压zip压缩文件 文件为jy.php可以直接执行,但是怎样将其加到CI框架中呢?? jy.php文件 <?php header("content-Type: ...
- 解压上传的zip文件流和文件
/** * 解压上传的zip文件流 * @param stream * @param outputDirectory */ public static String unzip(InputStream ...
- Flask保存或解压上传的文件
import os import uuid import shutil import zipfile from flask import Flask, render_template, request ...
- 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)
1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...
- java多图片上传--前端实现预览--图片压缩 、图片缩放,区域裁剪,水印,旋转,保持比例。
java多图片上传--前端实现预览 前端代码: https://pan.baidu.com/s/1cqKbmjBSXOhFX4HR1XGkyQ 解压后: java后台: <!--文件上传--&g ...
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- Delphi调用JAVA的WebService上传XML文件(XE10.2+WIN764)
相关资料:1.http://blog.csdn.net/luojianfeng/article/details/512198902.http://blog.csdn.net/avsuper/artic ...
- Java 利用FTP上传,下载文件,遍历文件目录
Java实现FTP上传下载文件的工具包有很多,这里我采用Java自带的API,实现FTP上传下载文件.另外JDK1.7以前的版本与其之后版本的API有了较大的改变了. 例如: JDK1.7之前 JDK ...
随机推荐
- 如何正确理解深度学习(Deep Learning)的概念
现在深度学习在机器学习领域是一个很热的概念,不过经过各种媒体的转载播报,这个概念也逐渐变得有些神话的感觉:例如,人们可能认为,深度学习是一种能够模拟出人脑的神经结构的机器学习方式,从而能够让计算机具有 ...
- Spring中后台字符串国际化
1.在工程的资源文件夹(source folder)中建立三个properties文件:messages.properties(默认).messages_zh_CN.properties(中文).me ...
- GitHub error “Failed to get HEAD”
cd /要提交的文件的文件夹下 比如要提交一个名为 demo的 程序, 那么先进入demo 的文件夹里面 然后 进行以下两步 git init (有时这个是不必要的,因为xcode 自 ...
- Error:No marked region found along edge. - Found along top edge.
android开发的时候,初次使用.9图片出现以下: Error:No marked region found along edge. - Found along top edge. 原因: 如图:上 ...
- C# 延迟初始化
一个对象的延迟初始化意味着该对象的创建将会延迟至第一次使用该对象时.(在本主题中,术语“延迟初始化”和“延迟实例化”是同义词.)延迟初始化主要用于提高性能,避免浪费计算,并减少程序内存要求. 以下是最 ...
- 1502: [NOI2005]月下柠檬树 - BZOJ
Description Input 文件的第1行包含一个整数n和一个实数alpha,表示柠檬树的层数和月亮的光线与地面夹角(单位为弧度).第2行包含n+1个实数h0,h1,h2,…,hn,表示树离地的 ...
- Matlab中mat2cell的使用
怎样用mat2cell将一个100*100的矩阵分成10个10*100的矩阵? 根据帮助中 c = mat2cell(x,m,n)应该这样写 mat2cell(x,[10 10 10 10 10 10 ...
- PhotoSwipe简介(PhotoSwipe是一个适合在触摸屏手机上使用的相册展示包)
官方介绍PhotoSwipe 是专为移动触摸设备设计的相册/画廊.兼容所有iPhone.iPad.黑莓6+,以及桌面浏览器.底层实现基于HTML/CSS/JavaScript,是一款免费开源的相册产品 ...
- HDU 1227 Fast Food (DP)
题目链接 题意 : 有n个饭店,要求建k个供应点,要求每个供应点一定要建造在某个饭店的位置上,然后饭店都到最近的供应点拿货,求出所有饭店到最近的供应点的最短距离. 思路 : 一开始没看出来是DP,后来 ...
- 0环境设置 - AUTOTRACE设置
Autotrace是sqlplus的一个工具,用来显示所执行查询的查询计划 设置步骤 • cd [ORACLE_HOME]/rdbms/admin• log into SQL*Plus as SYST ...