Java解压上传zip或rar文件,并解压遍历文件中的html的路径

时间:2024-05-06 16:05:55

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>