Java 主要使用ZipInputStream和ZipOutputStream实现压缩与解压功能。
public class ZipUtil {
private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
/**
* 功能描述: <br>
* 将多个文件,压缩成一个文件
*
* @param srcPath ["d:/1.txt","d:/2.txt"]
* @param outPath d:/1.zip
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static void zip(String[] srcPaths, String outPath) {
if (srcPaths == null || srcPaths.length == 0 || StringUtils.isEmpty(outPath)) {
logger.error("参数错误");
return;
}
List<File> srcList = new ArrayList<>();
for (String path : srcPaths) {
File file = new File(path);
if (file.exists() && !file.isDirectory()) {
srcList.add(file);
}
}
if (srcList.isEmpty()) {
logger.error("没有有效的输入文件");
return;
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outPath))) {
for (File file : srcList) {
compress(zos, file);
}
} catch (Exception e) {
logger.error("压缩异常", e);
}
}
private static void compress(ZipOutputStream zos, File file) {
try (InputStream is = new FileInputStream(file);) {
zos.putNextEntry(new ZipEntry(file.getName()));
int len = -1;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
zos.write(buf, 0, len);
}
} catch (Exception e) {
logger.error("压缩文件失败", e);
}
}
/**
* 功能描述: <br>
* 解压缩文件
*
* @param srcPath d:/1.zip
* @param outDir d:/unzip
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static void unzip(String srcPath, String outDir) {
File file = new File(srcPath);
if (!file.exists() || file.isDirectory()) {
logger.error("文件不存在或者是文件夹");
return;
}
File dir = new File(outDir);
if (!dir.exists()) {
dir.mkdirs();
}
try (InputStream in = new FileInputStream(file); ZipInputStream zipis = new ZipInputStream(in);) {
ZipEntry zipEntry;
while ((zipEntry = zipis.getNextEntry()) != null) {
if (zipEntry.isDirectory()) {
continue;
}
decompress(zipis, outDir + "/" + zipEntry.getName());
}
} catch (Exception e) {
logger.error("解压异常", e);
}
}
private static void decompress(ZipInputStream zipis, String outPath) {
try (OutputStream out = new FileOutputStream(outPath);) {
int len = -1;
byte[] buf = new byte[1024];
while ((len = zipis.read(buf)) != -1) {
out.write(buf, 0, len);
}
} catch (Exception e) {
logger.error("解压文件失败", e);
}
}
}