因项目中使用大量图片上传功能,请求次数过多,导致占用过多网络资源.优化改为压缩zip一次性上传.
测试数据: 10个文件 总共为1.8G 压缩总时长为1分10秒; 解压缩时长24秒
测试环境:ubuntu 13, jdk 1.8
缺点:1 压缩文件不能为文件夹
2 压缩比例不明显,文件大小没怎么缩小
/**
* 压缩
*
* @param files
* 压缩的文件
* @param zipPath
* 压缩zip存放路径
* @param original
* 是否删除原文件
* @throws Exception
*/
public static void zip(File[] files, String zipPath, boolean original) throws Exception {
if (files == null || files.length == 0) {
throw new Exception("file列表错误,不能为空");
}
if (StringUtils.isBlank(zipPath)) {
throw new Exception("压缩文件存放路径不能为空");
}
if (new File(zipPath).exists()) {
new File(zipPath).delete();
}
logger.info("{msg:'[{}]开始压缩,millis:[{}]'}", LocalDateTime.now().toString(), Instant.now().getMillis());
zipPath = StringUtils.replace(zipPath, "\\", "/");
File zipfile = new File(StringUtils.substringBeforeLast(zipPath, File.separator));
if (!zipfile.exists()) {
if (!zipfile.createNewFile()) {
throw new Exception("文件目录生成失败!");
}
}
for (File file : files) {
if (file.isDirectory()) {
throw new Exception("只能压缩文件,不能压缩文件夹");
}
}
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
byte[] buffer = new byte[8192];
zos = new ZipOutputStream(fos, Charset.forName("UTF-8"));
for (File file : files) {
ZipEntry entry = new ZipEntry(file.getName());
entry.setComment(file.getName() + ",大小:" + file.length());
entry.setSize(file.length());
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(file);
int read = 0;
while ((read = fis.read(buffer)) != -1) {
zos.write(buffer, 0, read);
}
fis.close();
}
} catch (Exception e) {
throw e;
} finally {
if (zos != null)
zos.close();
if (fos != null)
fos.close();
}
if (original) {
for (File file : files) {
file.delete();
}
}
logger.info("{msg:'[{}]压缩完成,millis:[{}]'}", LocalDateTime.now().toString(), Instant.now().getMillis());
}
/**
* 解压缩
*
* @param zipFile
* 需解压缩文件
* @param unzipfile
* 解压缩存放的文件夹名
* @throws Exception
*/
public static void unzip(String zipFile, String unzipfile) throws Exception {
if (!new File(zipFile).exists()) {
throw new Exception("解压缩文件不存在");
}
if (!new File(unzipfile).exists()) {
new File(unzipfile).mkdirs();
}
logger.info("{msg:'[{}]开始解压缩文件,millis:[{}]'}", LocalDateTime.now().toString(), Instant.now().getMillis());
ZipFile file = new ZipFile(zipFile);
byte[] buffer = new byte[8192];
Enumeration extends ZipEntry> e = file.entries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
File f = new File(unzipfile + File.separator + entry.getName());
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream fos = null;
InputStream is = null;
try {
fos = new FileOutputStream(f);
is = file.getInputStream(entry);
int read = 0;
while ((read = is.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
} catch (Exception e2) {
throw e2;
} finally {
if (is != null)
is.close();
if (fos != null)
fos.close();
}
}
logger.info("{msg:'[{}]解压缩文件完成,millis:[{}]'}", LocalDateTime.now().toString(), Instant.now().getMillis());
}
有更做优方法请指正.
QQ:376987715交流学习