package com.hgq.util; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.utils.IOUtils; import java.io.*; import java.util.Enumeration; /** * TODO 类的作用信息 * * @author huguangquan * @date 22-9-16 016 */ public class ZipUtil { public static final int BUFFER_SIZE = 2048; public static void unZip(File file, String destDir) throws IOException { // windows设置GBK编码,中文乱码问题 ZipFile zipFile = new ZipFile(file, "GBK"); byte[] buffer = new byte[BUFFER_SIZE]; ZipArchiveEntry entry; // 获取全部文件的迭代器,循环解压所有文件 Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); InputStream inputStream; while (entries.hasMoreElements()) { entry = entries.nextElement(); if (entry.isDirectory()) { continue; } File outputFile = new File(destDir + entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } inputStream = zipFile.getInputStream(entry); try (FileOutputStream fos = new FileOutputStream(outputFile)) { while (inputStream.read(buffer) > 0) { fos.write(buffer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } zipFile.close(); } /** * 解压 zip 文件 * * @param zipFileInputStream zip压缩文件输入流 * @param destDir zip 压缩文件解压后保存的目录 * @return 返回 zip 压缩文件里的文件名的 list * @throws Exception */ public static void unZip(InputStream zipFileInputStream, String destDir) throws Exception { ZipArchiveInputStream is = null; try { is = new ZipArchiveInputStream(zipFileInputStream, "GBK", true); ZipArchiveEntry entry = null; while ((entry = is.getNextZipEntry()) != null) { if (entry.isDirectory()) { File directory = new File(destDir, entry.getName()); directory.mkdirs(); } else { OutputStream os = null; try { // 解压的时候如果是无.dcm后缀的dicom文件,默认给文件加上.dcm后缀 os = new BufferedOutputStream(new FileOutputStream(new File(destDir, entry.getName())), BUFFER_SIZE); IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(os); } } } } catch (Exception e) { e.printStackTrace(); throw e; } finally { IOUtils.closeQuietly(is); } } }