Commit 956dd7e0 by 田超

Merge branch 'fixbug/zipusedirectory' into 'master'

Fixbug/zipusedirectory

See merge request rays/pcloud-common-parent!195
parents 4f4da885 a21e17f3
...@@ -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) { fileUrlList.add(new String[]{compressFileDTO.getFileName(), compressFileDTO.getFileUrl(),compressFileDTO.getDirName()});
String zipName = compressDTO.getCompressName() + "_" + index; if (totalFileSize > CUT_SIZE) {
UploadResultInfo uploadResultInfo = zip(fileUrlList, zipName); String zipName = compressDTO.getCompressName() + "_" + index;
uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl())); UploadResultInfo uploadResultInfo = zip(fileUrlList, zipName);
uploadResultInfo.setFileItemCount(fileUrlList.size()); uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
uploadResultInfos.add(uploadResultInfo); uploadResultInfo.setFileItemCount(fileUrlList.size());
// 零时变量复位 uploadResultInfos.add(uploadResultInfo);
totalFileSize = 0; // 零时变量复位
fileUrlList = Lists.newArrayList(); totalFileSize = 0;
index++; fileUrlList = Lists.newArrayList();
} index++;
} }
// 打包剩余总大小不足1G的文件 }
if (fileUrlList.size() > 0) { // 打包剩余总大小不足1G的文件
UploadResultInfo uploadResultInfo = zip(fileUrlList, compressDTO.getCompressName() + "_" + index); if (fileUrlList.size() > 0) {
uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl())); UploadResultInfo uploadResultInfo = zip(fileUrlList, compressDTO.getCompressName() + "_" + index);
uploadResultInfo.setFileItemCount(fileUrlList.size()); uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
uploadResultInfos.add(uploadResultInfo); uploadResultInfo.setFileItemCount(fileUrlList.size());
} uploadResultInfos.add(uploadResultInfo);
LOGGER.info("【压缩】分批次打包文件.<END>"); }
return uploadResultInfos; LOGGER.info("【压缩】分批次打包文件.<END>");
} return uploadResultInfos;
}
/**
* 压缩文件 /**
* * 压缩文件
* @param fileUrlList String[0]=文件名称, String[1]=文件地址 *
* @param zipName 压缩包的名称 * @param fileUrlList String[0]=文件名称, String[1]=文件地址
* @return * @param zipName 压缩包的名称
* @throws BizException * @return
*/ * @throws BizException
public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException { */
LOGGER.info("【压缩】压缩文件.<START>"); public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException {
if (ListUtils.isEmpty(fileUrlList)) { LOGGER.info("【压缩】压缩文件.<START>...");
return null; if (ListUtils.isEmpty(fileUrlList)) {
} return null;
String zipNameFormat = FileUtils.formatName(zipName); }
String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss(); String zipNameFormat = FileUtils.formatName(zipName);
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss();
// 检查临时文件夹是否存在,不存在就创建 String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
String fileFolderPath = FILE_LOCAL_PATH + tempZipName; // 检查临时文件夹是否存在,不存在就创建
FileUtils.isDir(fileFolderPath); String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
UploadResultInfo uploadResultInfo = null; FileUtils.isDir(fileFolderPath);
try { UploadResultInfo uploadResultInfo = null;
// 下载文件到文件夹中 try {
int idx = 1; // 下载文件到文件夹中
for (String[] files : fileUrlList) { int idx = 1;
String fileType = FileUtils.getFileType(files[1]); String downloadPath;
String fileName = FileUtils.formatName(files[0]); for (String[] files : fileUrlList) {
String downloadLocalPath = fileFolderPath + "/" + fileName + "_" + idx + "." + fileType; // 检查临时文件夹是否存在,不存在就创建
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath); if (files.length>2 && !StringUtil.isEmpty(files[2])) {
idx++; String catalogFolderPath = fileFolderPath + "/" + files[2];
} FileUtils.isDir(catalogFolderPath);
// 检查压缩包临时文件夹是否存在,不存在就创建 downloadPath = catalogFolderPath;
FileUtils.isDir(ZIP_FILE_PATH); } else {
CompressUtils.zip(fileFolderPath, zipFilePath); downloadPath = fileFolderPath;
// 上传文件到服务器中 }
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat); String fileType = FileUtils.getFileType(files[1]);
uploadResultInfo.setFileName(zipName); String fileName = FileUtils.formatName(files[0]);
} catch (Exception e) { String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType;
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!"); idx++;
} finally { }
// 删除产生的文件 // 检查压缩包临时文件夹是否存在,不存在就创建
FileUtils.deleteDirectory(fileFolderPath); FileUtils.isDir(ZIP_FILE_PATH);
FileUtils.deleteFile(zipFilePath); CompressUtils.zip(fileFolderPath, zipFilePath);
} // 上传文件到服务器中
LOGGER.info("【压缩】压缩文件.<END>"); uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat);
return uploadResultInfo; 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]=文件地址 FileUtils.deleteDirectory(fileFolderPath);
* @param zipName FileUtils.deleteFile(zipFilePath);
* @return }
* @throws BizException LOGGER.info("【压缩】压缩文件.<END>");
*/ return uploadResultInfo;
public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName) }
throws BizException {
LOGGER.info("【压缩】压缩文件.<START>"); /**
if (MapUtils.isEmpty(catalogFiles)) { * 压缩文件(带目录)
return null; *
} * @param catalogFiles key : 目录名 String[0]=文件名称, String[1]=文件地址
zipName = FileUtils.formatName(zipName); * @param zipName
String tempZipName = zipName + "_" + UUIDUitl.generateString(12); * @return
String parentPath = FILE_LOCAL_PATH + tempZipName; * @throws BizException
FileUtils.isDir(parentPath); */
for (String catalog : catalogFiles.keySet()) { public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName)
String downloadPath; throws BizException {
// 检查临时文件夹是否存在,不存在就创建 LOGGER.info("【压缩】压缩文件.<START>");
if (!StringUtil.isEmpty(catalog)) { if (MapUtils.isEmpty(catalogFiles)) {
String catalogFolderPath = parentPath + "/" + catalog; return null;
FileUtils.isDir(catalogFolderPath); }
downloadPath = catalogFolderPath; zipName = FileUtils.formatName(zipName);
} else { String tempZipName = zipName + "_" + UUIDUitl.generateString(12);
downloadPath = parentPath; String parentPath = FILE_LOCAL_PATH + tempZipName;
} FileUtils.isDir(parentPath);
List<String[]> fileUrlList = catalogFiles.get(catalog); for (String catalog : catalogFiles.keySet()) {
// 下载文件到文件夹中 String downloadPath;
int idx = 1; // 检查临时文件夹是否存在,不存在就创建
for (String[] files : fileUrlList) { if (!StringUtil.isEmpty(catalog)) {
String fileType = FileUtils.getFileType(files[1]); String catalogFolderPath = parentPath + "/" + catalog;
String fileName = FileUtils.formatName4Zip(files[0]); FileUtils.isDir(catalogFolderPath);
String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType; downloadPath = catalogFolderPath;
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath); } else {
idx++; downloadPath = parentPath;
} }
} List<String[]> fileUrlList = catalogFiles.get(catalog);
// 检查压缩包临时文件夹是否存在,不存在就创建 // 下载文件到文件夹中
FileUtils.isDir(ZIP_FILE_PATH); int idx = 1;
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; for (String[] files : fileUrlList) {
try { String fileType = FileUtils.getFileType(files[1]);
CompressUtils.zip(parentPath, zipFilePath); String fileName = FileUtils.formatName4Zip(files[0]);
} catch (Exception e) { String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType;
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!"); idx++;
} }
// 上传文件到服务器中 }
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName); // 检查压缩包临时文件夹是否存在,不存在就创建
// 删除产生的文件 FileUtils.isDir(ZIP_FILE_PATH);
FileUtils.deleteDirectory(parentPath); String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
FileUtils.deleteFile(zipFilePath); try {
LOGGER.info("【压缩】压缩文件.<END>"); CompressUtils.zip(parentPath, zipFilePath);
return uploadResultInfo; } catch (Exception e) {
} LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
/** }
* @param zipPath ZIP文件目录 // 上传文件到服务器中
* @param destDir 解压目录 UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
* @throws Exception // 删除产生的文件
* @Desc ZIP文件解压 FileUtils.deleteDirectory(parentPath);
*/ FileUtils.deleteFile(zipFilePath);
private static void unzip(String zipPath, String destDir) throws Exception { LOGGER.info("【压缩】压缩文件.<END>");
try { return uploadResultInfo;
Project p = new Project(); }
Expand e = new Expand();
e.setProject(p); /**
e.setSrc(new File(zipPath)); * @param zipPath ZIP文件目录
e.setOverwrite(false); * @param destDir 解压目录
e.setDest(new File(destDir)); * @throws Exception
e.setEncoding("gbk"); * @Desc ZIP文件解压
e.execute(); */
} catch (Exception e) { private static void unzip(String zipPath, String destDir) throws Exception {
throw e; try {
} Project p = new Project();
} Expand e = new Expand();
e.setProject(p);
/** e.setSrc(new File(zipPath));
* @param rarPath rar路径 e.setOverwrite(false);
* @param destDir 解压到的文件夹 e.setDest(new File(destDir));
* @throws Exception e.setEncoding("gbk");
* @Desc rar文件解压 e.execute();
*/ } catch (Exception e) {
public static void unrar(String rarPath, String destDir) throws Exception { throw e;
if (!rarPath.toLowerCase().endsWith(".rar")) { }
throw new Exception("非rar文件!"); }
}
File dstDiretory = new File(destDir); /**
if (!dstDiretory.exists()) { * @param rarPath rar路径
dstDiretory.mkdirs(); * @param destDir 解压到的文件夹
} * @throws Exception
Archive a = new Archive(new File(rarPath)); * @Desc rar文件解压
if (a != null) { */
FileHeader fh = a.nextFileHeader(); public static void unrar(String rarPath, String destDir) throws Exception {
while (fh != null) { if (!rarPath.toLowerCase().endsWith(".rar")) {
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW(); throw new Exception("非rar文件!");
if (fh.isDirectory()) { }
File fol = new File(destDir + File.separator + fileName); File dstDiretory = new File(destDir);
fol.mkdirs(); if (!dstDiretory.exists()) {
} else { dstDiretory.mkdirs();
File out = new File(destDir + File.separator + fileName.trim()); }
if (!out.exists()) { Archive a = new Archive(new File(rarPath));
if (!out.getParentFile().exists()) { if (a != null) {
out.getParentFile().mkdirs(); FileHeader fh = a.nextFileHeader();
} while (fh != null) {
out.createNewFile(); String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
} if (fh.isDirectory()) {
FileOutputStream os = new FileOutputStream(out); File fol = new File(destDir + File.separator + fileName);
a.extractFile(fh, os); fol.mkdirs();
os.close(); } else {
} File out = new File(destDir + File.separator + fileName.trim());
fh = a.nextFileHeader(); if (!out.exists()) {
} if (!out.getParentFile().exists()) {
a.close(); out.getParentFile().mkdirs();
} }
} out.createNewFile();
}
/** FileOutputStream os = new FileOutputStream(out);
* @param sourceFile zip或者rar文件路径 a.extractFile(fh, os);
* @param destDir 解压目录 os.close();
* @throws Exception }
* @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文件路径
// 根据类型,进行相应的解压缩 * @param destDir 解压目录
String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase(); * @throws Exception
if (type.equals("zip")) { * @Desc 解压缩文件
unzip(sourceFile, destDir); */
} else if (type.equals("rar")) { public static void deCompress(String sourceFile, String destDir) throws Exception {
unrar(sourceFile, destDir); // 保证文件夹路径最后是"/"或者"\"
} else { char lastChar = destDir.charAt(destDir.length() - 1);
throw new Exception("只支持zip和rar格式的压缩包!"); if (lastChar != '/' && lastChar != '\\') {
} destDir += File.separator;
} }
// 根据类型,进行相应的解压缩
/** String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase();
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename if (type.equals("zip")) {
* 压缩后的文件完整的路径名称 @throws unzip(sourceFile, destDir);
*/ } else if (type.equals("rar")) {
public static void zip(String inputFilename, String zipFilename) throws IOException { unrar(sourceFile, destDir);
File inputFile = new File(inputFilename); } else {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename)); throw new Exception("只支持zip和rar格式的压缩包!");
try { }
compress(inputFile, out); }
// zip(inputFile, out, "");
} catch (Exception e) { /**
throw e; * @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename
} finally { * 压缩后的文件完整的路径名称 @throws
out.close(); */
} 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);
* // zip(inputFile, out, "");
* @param inputFile } catch (Exception e) {
* @param out throw e;
* @param base } finally {
* @throws IOException 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 + "/")); * @param inputFile
base = base.length() == 0 ? "" : base + "/"; * @param out
for (int i = 0; i < inputFiles.length; i++) { * @param base
zip(inputFiles[i], out, base + inputFiles[i].getName()); * @throws IOException
} */
} else { @SuppressWarnings("unused")
if (base.length() > 0) { private static void zip(File inputFile, ZipOutputStream out, String base) throws IOException {
out.putNextEntry(new ZipEntry(base)); if (inputFile.isDirectory()) {
} else { File[] inputFiles = inputFile.listFiles();
out.putNextEntry(new ZipEntry(inputFile.getName())); if (!base.equals(""))
} out.putNextEntry(new ZipEntry(base + "/"));
FileInputStream in = new FileInputStream(inputFile); base = base.length() == 0 ? "" : base + "/";
try { for (int i = 0; i < inputFiles.length; i++) {
int c; zip(inputFiles[i], out, base + inputFiles[i].getName());
byte[] by = new byte[1024]; }
while ((c = in.read(by)) != -1) { } else {
out.write(by, 0, c); if (base.length() > 0) {
} out.putNextEntry(new ZipEntry(base));
} catch (IOException e) { } else {
throw e; out.putNextEntry(new ZipEntry(inputFile.getName()));
} finally { }
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);
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, }
* } catch (IOException e) {
* @param src throw e;
* @param zos } finally {
*/ in.close();
private static void compress(File src, ZipOutputStream zos) { }
compressbyType(src, zos, "", true); }
} }
/** /**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
* *
* @param src * @param src
* @param zos * @param zos
* @param baseDir */
*/ private static void compress(File src, ZipOutputStream zos) {
private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) { compressbyType(src, zos, "", true);
if (!src.exists()) }
return;
// 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法; /**
if (src.isFile()) { * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
// src是文件,调用此方法 *
compressFile(src, zos, baseDir); * @param src
} else if (src.isDirectory()) { * @param zos
// src是文件夹,调用此方法 * @param baseDir
compressDir(src, zos, baseDir, isFirst); */
private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) {
} if (!src.exists())
} return;
// 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
/** if (src.isFile()) {
* 压缩文件 // src是文件,调用此方法
*/ compressFile(src, zos, baseDir);
private static void compressFile(File file, ZipOutputStream zos, String baseDir) { } else if (src.isDirectory()) {
if (!file.exists()) // src是文件夹,调用此方法
return; compressDir(src, zos, baseDir, isFirst);
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]; * 压缩文件
while ((count = bis.read(buf)) != -1) { */
zos.write(buf, 0, count); private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
} if (!file.exists())
bis.close(); return;
} catch (Exception e) { 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];
*/ while ((count = bis.read(buf)) != -1) {
private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) { zos.write(buf, 0, count);
if (!dir.exists()) }
return; bis.close();
File[] files = dir.listFiles(); } catch (Exception e) {
if (files.length == 0 && !StringUtil.isEmpty(baseDir)) { }
try { }
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) { /**
e.printStackTrace(); * 压缩文件夹
} */
} private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) {
for (File file : files) { if (!dir.exists())
if (isFirst) { return;
compressbyType(file, zos, baseDir, false); File[] files = dir.listFiles();
} else { if (files.length == 0 && !StringUtil.isEmpty(baseDir)) {
compressbyType(file, zos, baseDir + dir.getName() + File.separator, false); try {
} zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} } catch (IOException e) {
} e.printStackTrace();
}
/** }
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename for (File file : files) {
* 压缩后的文件完整的路径名称 @throws if (isFirst) {
*/ compressbyType(file, zos, baseDir, false);
public static void zip(String inputFilename, ZipOutputStream out) throws IOException { } else {
File inputFile = new File(inputFilename); compressbyType(file, zos, baseDir + dir.getName() + File.separator, false);
try { }
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, 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