public class ZipFileUtil {
/**
* 压缩文件为zip
*
* @return java.io.File
* @Author hl1314
* @Date 11:48 2019-07-22
* @Param [sourceDir, zipFilePath]
**/
public static File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
return doZip(file, zipFile);
}
/**
* 压缩文件为zip
*
* @return java.io.File
* @Author hl1314
* @Date 11:48 2019-07-22
* @Param [sourceDir, zipFilePath]
**/
public static File doZip(File file, File zipFile) throws IOException {
// 创建写出流操作
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) {
String basePath = null;
// 获取目录
if (file.isDirectory()) {
basePath = file.getPath();
} else {
basePath = file.getParent();
}
zipFile(file, basePath, zos);
}
return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private static void zipFile(File source, String basePath, ZipOutputStream zos) throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}
InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try {
for (File file : files) {
pathName = file.getPath().substring(basePath.length() + 1);
if (file.isDirectory()) {
pathName = pathName + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
} else {
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
}
}
} finally {
if (is != null) {
is.close();
}
}
}
/**
* 解压zip文件
*
* @return java.util.Map<java.lang.String, byte [ ]>
* @Author hl1314
* @Date 17:09 2019-07-22
* @Param [inputStream]
**/
public static Map<String, byte[]> uncompress(InputStream inputStream) throws IOException {
ZipInputStream zis = new ZipInputStream(inputStream);
Map<String, byte[]> map = new HashMap<>(1);
ZipEntry ze;
byte[] buffer;
while (((ze = zis.getNextEntry()) != null) && !ze.isDirectory()) {
String name = ze.getName();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
buffer = new byte[1024];
int length;
while ((length = zis.read(buffer, 0, buffer.length)) > -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
map.put(name, byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
}
zis.close();
return map;
}
}