Commit 5ccb8ba8 by zhangyang

[none] 压缩资源包增加目录处理

parent 4f4da885
...@@ -59,6 +59,9 @@ public class CompressDTO extends BaseDto { ...@@ -59,6 +59,9 @@ public class CompressDTO extends BaseDto {
@ApiModelProperty(name = "文件大小", dataType = "Long") @ApiModelProperty(name = "文件大小", dataType = "Long")
private long fileSize; private long fileSize;
@ApiModelProperty(name = "目录名称", dataType = "String")
private String dirName;
public String getFileName() { public String getFileName() {
return fileName; return fileName;
} }
...@@ -83,6 +86,14 @@ public class CompressDTO extends BaseDto { ...@@ -83,6 +86,14 @@ public class CompressDTO extends BaseDto {
this.fileSize = fileSize; this.fileSize = fileSize;
} }
public String getDirName() {
return dirName;
}
public void setDirName(String dirName) {
this.dirName = dirName;
}
@Override @Override
public String toString() { public String toString() {
return "CompressFileDTO " + JSON.toJSONString(this); return "CompressFileDTO " + JSON.toJSONString(this);
......
package com.pcloud.common.utils.zip; package com.pcloud.common.utils.zip;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.HashMap;
import java.util.Map; import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.apache.tools.ant.Project; import org.apache.commons.collections.MapUtils;
import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.Project;
import org.apache.tools.zip.ZipEntry; import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipOutputStream; import org.apache.tools.zip.ZipEntry;
import org.slf4j.Logger; import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader; import com.github.junrar.Archive;
import com.google.common.collect.Lists; import com.github.junrar.rarfile.FileHeader;
import com.pcloud.common.constant.OSConstant; import com.google.common.collect.Lists;
import com.pcloud.common.dto.CompressDTO; import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.dto.CompressDTO.CompressFileDTO; import com.pcloud.common.dto.CompressDTO;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.dto.CompressDTO.CompressFileDTO;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.FileUtils; import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.ListUtils; import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.LocalDateUtils; import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.UUIDUitl; import com.pcloud.common.utils.LocalDateUtils;
import com.pcloud.common.utils.aliyun.OssUtils; import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.string.StringUtil;
/**
* @描述:文件压缩和解压缩 /**
* @作者:songx * @描述:文件压缩和解压缩
* @创建时间:2016年7月13日,上午11:36:37 @版本:1.0 * @作者:songx
*/ * @创建时间:2016年7月13日,上午11:36:37 @版本:1.0
public class CompressUtils { */
public class CompressUtils {
/**
* /**
*/ *
private static final Logger LOGGER = LoggerFactory.getLogger(CompressUtils.class); */
private static final Logger LOGGER = LoggerFactory.getLogger(CompressUtils.class);
/**
* 压缩文件临时基础路径 /**
*/ * 压缩文件临时基础路径
private static String FILE_LOCAL_PATH = OSConstant.USERDIR + "/download/"; */
private static String FILE_LOCAL_PATH = OSConstant.USERDIR + "/download/";
/**
* 压缩文件临时基础路径 /**
*/ * 压缩文件临时基础路径
private static String ZIP_FILE_PATH = OSConstant.USERDIR + "/zip/"; */
private static String ZIP_FILE_PATH = OSConstant.USERDIR + "/zip/";
/**
* 分拆大小值 /**
*/ * 分拆大小值
private static long CUT_SIZE = 1 * 1024 * 1024 * 1024; */
private static long CUT_SIZE = 1 * 1024 * 1024 * 1024;
/**
* 分批次打包,压缩文件集超过指定大小后,分多个包压缩,目前限定1个压缩包1G。 /**
* * 分批次打包,压缩文件集超过指定大小后,分多个包压缩,目前限定1个压缩包1G。
* @param compressDTO *
* @return * @param compressDTO
* @throws BizException * @return
*/ * @throws BizException
public static List<UploadResultInfo> zips(CompressDTO compressDTO) throws BizException { */
LOGGER.info("【压缩】分批次打包文件.<START>.[compressDTO]=" + compressDTO); public static List<UploadResultInfo> zips(CompressDTO compressDTO) throws BizException {
if (compressDTO == null) { LOGGER.info("【压缩】分批次打包文件.<START>.[compressDTO]=" + compressDTO);
return null; if (compressDTO == null) {
} return null;
List<CompressFileDTO> compressFileDTOs = compressDTO.getCompressFileDTOs(); }
if (ListUtils.isEmpty(compressFileDTOs)) { List<CompressFileDTO> compressFileDTOs = compressDTO.getCompressFileDTOs();
return null; if (ListUtils.isEmpty(compressFileDTOs)) {
} return null;
List<UploadResultInfo> uploadResultInfos = Lists.newArrayList(); }
List<String[]> fileUrlList = Lists.newArrayList(); List<UploadResultInfo> uploadResultInfos = Lists.newArrayList();
long totalFileSize = 0; List<String[]> fileUrlList = Lists.newArrayList();
int size = compressFileDTOs.size(); long totalFileSize = 0;
int index = 1; int size = compressFileDTOs.size();
for (int i = 0; i < size; i++) { int index = 1;
CompressFileDTO compressFileDTO = compressFileDTOs.get(i); for (int i = 0; i < size; i++) {
totalFileSize += compressFileDTO.getFileSize(); CompressFileDTO compressFileDTO = compressFileDTOs.get(i);
fileUrlList.add(new String[]{compressFileDTO.getFileName(), compressFileDTO.getFileUrl()}); totalFileSize += compressFileDTO.getFileSize();
if (totalFileSize > CUT_SIZE) { String dirName = compressFileDTO.getDirName();
String zipName = compressDTO.getCompressName() + "_" + index; fileUrlList.add(new String[]{compressFileDTO.getFileName(), compressFileDTO.getFileUrl(),compressFileDTO.getDirName()});
UploadResultInfo uploadResultInfo = zip(fileUrlList, zipName); if (totalFileSize > CUT_SIZE) {
uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl())); String zipName = compressDTO.getCompressName() + "_" + index;
uploadResultInfo.setFileItemCount(fileUrlList.size()); UploadResultInfo uploadResultInfo = zip(fileUrlList, zipName);
uploadResultInfos.add(uploadResultInfo); uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
// 零时变量复位 uploadResultInfo.setFileItemCount(fileUrlList.size());
totalFileSize = 0; uploadResultInfos.add(uploadResultInfo);
fileUrlList = Lists.newArrayList(); // 零时变量复位
index++; totalFileSize = 0;
} fileUrlList = Lists.newArrayList();
} index++;
// 打包剩余总大小不足1G的文件 }
if (fileUrlList.size() > 0) { }
UploadResultInfo uploadResultInfo = zip(fileUrlList, compressDTO.getCompressName() + "_" + index); // 打包剩余总大小不足1G的文件
uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl())); if (fileUrlList.size() > 0) {
uploadResultInfo.setFileItemCount(fileUrlList.size()); UploadResultInfo uploadResultInfo = zip(fileUrlList, compressDTO.getCompressName() + "_" + index);
uploadResultInfos.add(uploadResultInfo); uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
} uploadResultInfo.setFileItemCount(fileUrlList.size());
LOGGER.info("【压缩】分批次打包文件.<END>"); uploadResultInfos.add(uploadResultInfo);
return uploadResultInfos; }
} LOGGER.info("【压缩】分批次打包文件.<END>");
return uploadResultInfos;
/** }
* 压缩文件
* /**
* @param fileUrlList String[0]=文件名称, String[1]=文件地址 * 压缩文件
* @param zipName 压缩包的名称 *
* @return * @param fileUrlList String[0]=文件名称, String[1]=文件地址
* @throws BizException * @param zipName 压缩包的名称
*/ * @return
public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException { * @throws BizException
LOGGER.info("【压缩】压缩文件.<START>"); */
if (ListUtils.isEmpty(fileUrlList)) { public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException {
return null; LOGGER.info("【压缩】压缩文件.<START>...");
} if (ListUtils.isEmpty(fileUrlList)) {
String zipNameFormat = FileUtils.formatName(zipName); return null;
String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss(); }
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; String zipNameFormat = FileUtils.formatName(zipName);
// 检查临时文件夹是否存在,不存在就创建 String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss();
String fileFolderPath = FILE_LOCAL_PATH + tempZipName; String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
FileUtils.isDir(fileFolderPath); // 检查临时文件夹是否存在,不存在就创建
UploadResultInfo uploadResultInfo = null; String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
try { FileUtils.isDir(fileFolderPath);
// 下载文件到文件夹中 UploadResultInfo uploadResultInfo = null;
int idx = 1; try {
for (String[] files : fileUrlList) { // 下载文件到文件夹中
String fileType = FileUtils.getFileType(files[1]); int idx = 1;
String fileName = FileUtils.formatName(files[0]); String downloadPath;
String downloadLocalPath = fileFolderPath + "/" + fileName + "_" + idx + "." + fileType; for (String[] files : fileUrlList) {
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath); // 检查临时文件夹是否存在,不存在就创建
idx++; if (files.length>2 && !StringUtil.isEmpty(files[2])) {
} String catalogFolderPath = fileFolderPath + "/" + files[2];
// 检查压缩包临时文件夹是否存在,不存在就创建 FileUtils.isDir(catalogFolderPath);
FileUtils.isDir(ZIP_FILE_PATH); downloadPath = catalogFolderPath;
CompressUtils.zip(fileFolderPath, zipFilePath); } else {
// 上传文件到服务器中 downloadPath = fileFolderPath;
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat); }
uploadResultInfo.setFileName(zipName); String fileType = FileUtils.getFileType(files[1]);
} catch (Exception e) { String fileName = FileUtils.formatName(files[0]);
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType;
throw new FileException(FileException.ZIP_ERROR, "压缩失败!"); FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
} finally { idx++;
// 删除产生的文件 }
FileUtils.deleteDirectory(fileFolderPath); // 检查压缩包临时文件夹是否存在,不存在就创建
FileUtils.deleteFile(zipFilePath); FileUtils.isDir(ZIP_FILE_PATH);
} CompressUtils.zip(fileFolderPath, zipFilePath);
LOGGER.info("【压缩】压缩文件.<END>"); // 上传文件到服务器中
return uploadResultInfo; uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat);
} uploadResultInfo.setFileName(zipName);
} catch (Exception e) {
/** LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
* 压缩文件(带目录) throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
* } finally {
* @param catalogFiles key : 目录名 String[0]=文件名称, String[1]=文件地址 // 删除产生的文件
* @param zipName FileUtils.deleteDirectory(fileFolderPath);
* @return FileUtils.deleteFile(zipFilePath);
* @throws BizException }
*/ LOGGER.info("【压缩】压缩文件.<END>");
public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName) return uploadResultInfo;
throws BizException { }
LOGGER.info("【压缩】压缩文件.<START>");
if (MapUtils.isEmpty(catalogFiles)) { /**
return null; * 压缩文件(带目录)
} *
zipName = FileUtils.formatName(zipName); * @param catalogFiles key : 目录名 String[0]=文件名称, String[1]=文件地址
String tempZipName = zipName + "_" + UUIDUitl.generateString(12); * @param zipName
String parentPath = FILE_LOCAL_PATH + tempZipName; * @return
FileUtils.isDir(parentPath); * @throws BizException
for (String catalog : catalogFiles.keySet()) { */
String downloadPath; public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName)
// 检查临时文件夹是否存在,不存在就创建 throws BizException {
if (!StringUtil.isEmpty(catalog)) { LOGGER.info("【压缩】压缩文件.<START>");
String catalogFolderPath = parentPath + "/" + catalog; if (MapUtils.isEmpty(catalogFiles)) {
FileUtils.isDir(catalogFolderPath); return null;
downloadPath = catalogFolderPath; }
} else { zipName = FileUtils.formatName(zipName);
downloadPath = parentPath; String tempZipName = zipName + "_" + UUIDUitl.generateString(12);
} String parentPath = FILE_LOCAL_PATH + tempZipName;
List<String[]> fileUrlList = catalogFiles.get(catalog); FileUtils.isDir(parentPath);
// 下载文件到文件夹中 for (String catalog : catalogFiles.keySet()) {
int idx = 1; String downloadPath;
for (String[] files : fileUrlList) { // 检查临时文件夹是否存在,不存在就创建
String fileType = FileUtils.getFileType(files[1]); if (!StringUtil.isEmpty(catalog)) {
String fileName = FileUtils.formatName4Zip(files[0]); String catalogFolderPath = parentPath + "/" + catalog;
String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType; FileUtils.isDir(catalogFolderPath);
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath); downloadPath = catalogFolderPath;
idx++; } else {
} downloadPath = parentPath;
} }
// 检查压缩包临时文件夹是否存在,不存在就创建 List<String[]> fileUrlList = catalogFiles.get(catalog);
FileUtils.isDir(ZIP_FILE_PATH); // 下载文件到文件夹中
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; int idx = 1;
try { for (String[] files : fileUrlList) {
CompressUtils.zip(parentPath, zipFilePath); String fileType = FileUtils.getFileType(files[1]);
} catch (Exception e) { String fileName = FileUtils.formatName4Zip(files[0]);
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType;
throw new FileException(FileException.ZIP_ERROR, "压缩失败!"); FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
} idx++;
// 上传文件到服务器中 }
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName); }
// 删除产生的文件 // 检查压缩包临时文件夹是否存在,不存在就创建
FileUtils.deleteDirectory(parentPath); FileUtils.isDir(ZIP_FILE_PATH);
FileUtils.deleteFile(zipFilePath); String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
LOGGER.info("【压缩】压缩文件.<END>"); try {
return uploadResultInfo; CompressUtils.zip(parentPath, zipFilePath);
} } catch (Exception e) {
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
/** throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
* @param zipPath ZIP文件目录 }
* @param destDir 解压目录 // 上传文件到服务器中
* @throws Exception UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
* @Desc ZIP文件解压 // 删除产生的文件
*/ FileUtils.deleteDirectory(parentPath);
private static void unzip(String zipPath, String destDir) throws Exception { FileUtils.deleteFile(zipFilePath);
try { LOGGER.info("【压缩】压缩文件.<END>");
Project p = new Project(); return uploadResultInfo;
Expand e = new Expand(); }
e.setProject(p);
e.setSrc(new File(zipPath)); /**
e.setOverwrite(false); * @param zipPath ZIP文件目录
e.setDest(new File(destDir)); * @param destDir 解压目录
e.setEncoding("gbk"); * @throws Exception
e.execute(); * @Desc ZIP文件解压
} catch (Exception e) { */
throw e; private static void unzip(String zipPath, String destDir) throws Exception {
} try {
} Project p = new Project();
Expand e = new Expand();
/** e.setProject(p);
* @param rarPath rar路径 e.setSrc(new File(zipPath));
* @param destDir 解压到的文件夹 e.setOverwrite(false);
* @throws Exception e.setDest(new File(destDir));
* @Desc rar文件解压 e.setEncoding("gbk");
*/ e.execute();
public static void unrar(String rarPath, String destDir) throws Exception { } catch (Exception e) {
if (!rarPath.toLowerCase().endsWith(".rar")) { throw e;
throw new Exception("非rar文件!"); }
} }
File dstDiretory = new File(destDir);
if (!dstDiretory.exists()) { /**
dstDiretory.mkdirs(); * @param rarPath rar路径
} * @param destDir 解压到的文件夹
Archive a = new Archive(new File(rarPath)); * @throws Exception
if (a != null) { * @Desc rar文件解压
FileHeader fh = a.nextFileHeader(); */
while (fh != null) { public static void unrar(String rarPath, String destDir) throws Exception {
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW(); if (!rarPath.toLowerCase().endsWith(".rar")) {
if (fh.isDirectory()) { throw new Exception("非rar文件!");
File fol = new File(destDir + File.separator + fileName); }
fol.mkdirs(); File dstDiretory = new File(destDir);
} else { if (!dstDiretory.exists()) {
File out = new File(destDir + File.separator + fileName.trim()); dstDiretory.mkdirs();
if (!out.exists()) { }
if (!out.getParentFile().exists()) { Archive a = new Archive(new File(rarPath));
out.getParentFile().mkdirs(); if (a != null) {
} FileHeader fh = a.nextFileHeader();
out.createNewFile(); while (fh != null) {
} String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
FileOutputStream os = new FileOutputStream(out); if (fh.isDirectory()) {
a.extractFile(fh, os); File fol = new File(destDir + File.separator + fileName);
os.close(); fol.mkdirs();
} } else {
fh = a.nextFileHeader(); File out = new File(destDir + File.separator + fileName.trim());
} if (!out.exists()) {
a.close(); if (!out.getParentFile().exists()) {
} out.getParentFile().mkdirs();
} }
out.createNewFile();
/** }
* @param sourceFile zip或者rar文件路径 FileOutputStream os = new FileOutputStream(out);
* @param destDir 解压目录 a.extractFile(fh, os);
* @throws Exception os.close();
* @Desc 解压缩文件 }
*/ fh = a.nextFileHeader();
public static void deCompress(String sourceFile, String destDir) throws Exception { }
// 保证文件夹路径最后是"/"或者"\" a.close();
char lastChar = destDir.charAt(destDir.length() - 1); }
if (lastChar != '/' && lastChar != '\\') { }
destDir += File.separator;
} /**
// 根据类型,进行相应的解压缩 * @param sourceFile zip或者rar文件路径
String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase(); * @param destDir 解压目录
if (type.equals("zip")) { * @throws Exception
unzip(sourceFile, destDir); * @Desc 解压缩文件
} else if (type.equals("rar")) { */
unrar(sourceFile, destDir); public static void deCompress(String sourceFile, String destDir) throws Exception {
} else { // 保证文件夹路径最后是"/"或者"\"
throw new Exception("只支持zip和rar格式的压缩包!"); char lastChar = destDir.charAt(destDir.length() - 1);
} if (lastChar != '/' && lastChar != '\\') {
} destDir += File.separator;
}
/** // 根据类型,进行相应的解压缩
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase();
* 压缩后的文件完整的路径名称 @throws if (type.equals("zip")) {
*/ unzip(sourceFile, destDir);
public static void zip(String inputFilename, String zipFilename) throws IOException { } else if (type.equals("rar")) {
File inputFile = new File(inputFilename); unrar(sourceFile, destDir);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename)); } else {
try { throw new Exception("只支持zip和rar格式的压缩包!");
compress(inputFile, out); }
// zip(inputFile, out, ""); }
} catch (Exception e) {
throw e; /**
} finally { * @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename
out.close(); * 压缩后的文件完整的路径名称 @throws
} */
} public static void zip(String inputFilename, String zipFilename) throws IOException {
File inputFile = new File(inputFilename);
/** ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));
* 压缩方法 try {
* compress(inputFile, out);
* @param inputFile // zip(inputFile, out, "");
* @param out } catch (Exception e) {
* @param base throw e;
* @throws IOException } finally {
*/ out.close();
@SuppressWarnings("unused") }
private static void zip(File inputFile, ZipOutputStream out, String base) throws IOException { }
if (inputFile.isDirectory()) {
File[] inputFiles = inputFile.listFiles(); /**
if (!base.equals("")) * 压缩方法
out.putNextEntry(new ZipEntry(base + "/")); *
base = base.length() == 0 ? "" : base + "/"; * @param inputFile
for (int i = 0; i < inputFiles.length; i++) { * @param out
zip(inputFiles[i], out, base + inputFiles[i].getName()); * @param base
} * @throws IOException
} else { */
if (base.length() > 0) { @SuppressWarnings("unused")
out.putNextEntry(new ZipEntry(base)); private static void zip(File inputFile, ZipOutputStream out, String base) throws IOException {
} else { if (inputFile.isDirectory()) {
out.putNextEntry(new ZipEntry(inputFile.getName())); File[] inputFiles = inputFile.listFiles();
} if (!base.equals(""))
FileInputStream in = new FileInputStream(inputFile); out.putNextEntry(new ZipEntry(base + "/"));
try { base = base.length() == 0 ? "" : base + "/";
int c; for (int i = 0; i < inputFiles.length; i++) {
byte[] by = new byte[1024]; zip(inputFiles[i], out, base + inputFiles[i].getName());
while ((c = in.read(by)) != -1) { }
out.write(by, 0, c); } else {
} if (base.length() > 0) {
} catch (IOException e) { out.putNextEntry(new ZipEntry(base));
throw e; } else {
} finally { out.putNextEntry(new ZipEntry(inputFile.getName()));
in.close(); }
} FileInputStream in = new FileInputStream(inputFile);
} try {
} int c;
byte[] by = new byte[1024];
/** while ((c = in.read(by)) != -1) {
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, out.write(by, 0, c);
* }
* @param src } catch (IOException e) {
* @param zos throw e;
*/ } finally {
private static void compress(File src, ZipOutputStream zos) { in.close();
compressbyType(src, zos, "", true); }
} }
}
/**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, /**
* * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
* @param src *
* @param zos * @param src
* @param baseDir * @param zos
*/ */
private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) { private static void compress(File src, ZipOutputStream zos) {
if (!src.exists()) compressbyType(src, zos, "", true);
return; }
// 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
if (src.isFile()) { /**
// src是文件,调用此方法 * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
compressFile(src, zos, baseDir); *
} else if (src.isDirectory()) { * @param src
// src是文件夹,调用此方法 * @param zos
compressDir(src, zos, baseDir, isFirst); * @param baseDir
*/
} private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) {
} if (!src.exists())
return;
/** // 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
* 压缩文件 if (src.isFile()) {
*/ // src是文件,调用此方法
private static void compressFile(File file, ZipOutputStream zos, String baseDir) { compressFile(src, zos, baseDir);
if (!file.exists()) } else if (src.isDirectory()) {
return; // src是文件夹,调用此方法
try { compressDir(src, zos, baseDir, isFirst);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName()); }
zos.putNextEntry(entry); }
int count;
byte[] buf = new byte[1024]; /**
while ((count = bis.read(buf)) != -1) { * 压缩文件
zos.write(buf, 0, count); */
} private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
bis.close(); if (!file.exists())
} catch (Exception e) { return;
} try {
} BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
/** zos.putNextEntry(entry);
* 压缩文件夹 int count;
*/ byte[] buf = new byte[1024];
private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) { while ((count = bis.read(buf)) != -1) {
if (!dir.exists()) zos.write(buf, 0, count);
return; }
File[] files = dir.listFiles(); bis.close();
if (files.length == 0 && !StringUtil.isEmpty(baseDir)) { } catch (Exception e) {
try { }
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator)); }
} catch (IOException e) {
e.printStackTrace(); /**
} * 压缩文件夹
} */
for (File file : files) { private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) {
if (isFirst) { if (!dir.exists())
compressbyType(file, zos, baseDir, false); return;
} else { File[] files = dir.listFiles();
compressbyType(file, zos, baseDir + dir.getName() + File.separator, false); if (files.length == 0 && !StringUtil.isEmpty(baseDir)) {
} try {
} zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} } catch (IOException e) {
e.printStackTrace();
/** }
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename }
* 压缩后的文件完整的路径名称 @throws for (File file : files) {
*/ if (isFirst) {
public static void zip(String inputFilename, ZipOutputStream out) throws IOException { compressbyType(file, zos, baseDir, false);
File inputFile = new File(inputFilename); } else {
try { compressbyType(file, zos, baseDir + dir.getName() + File.separator, false);
compress(inputFile, out); }
// zip(inputFile, out, ""); }
} catch (Exception e) { }
throw e;
} finally { /**
out.close(); * @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename
} * 压缩后的文件完整的路径名称 @throws
} */
} public static void zip(String inputFilename, ZipOutputStream out) throws IOException {
File inputFile = new File(inputFilename);
try {
compress(inputFile, out);
// zip(inputFile, out, "");
} catch (Exception e) {
throw e;
} finally {
out.close();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment