1.添加依赖
<dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>1.3.2</version> </dependency>
2.编写工具类
public class UnZipUtils { /** * 解密并解压zip文件,提取message文件中信息数据 * * @param zipFile 原始文件路径 * @param password 解压文件密码(可以为空) */ public static JSONArray unZip(File zipFile, String password) throws Exception { JSONArray jsonArray = new JSONArray(); ZipFile zFile = new ZipFile(zipFile); // 首先创建ZipFile指向磁盘上的.zip文件 zFile.setFileNameCharset("GBK"); if (zFile.isEncrypted()) { zFile.setPassword(password.toCharArray()); // 设置密码 } List<FileHeader> headerList = zFile.getFileHeaders(); for (FileHeader fileHeader : headerList) { BufferedReader reader = null; StringBuffer sbf = new StringBuffer(); ZipInputStream inputStream = zFile.getInputStream(fileHeader); try { reader = new BufferedReader(new InputStreamReader(inputStream)); String tempStr; while ((tempStr = reader.readLine()) != null) { sbf.append(tempStr); } reader.close(); String str = sbf.toString(); str = str.replace("}", "},"); str = str.substring(str.indexOf("{"), str.lastIndexOf("}") + 1); str = "[" + str + "]"; jsonArray = JSON.parseArray(str); } finally { if (reader != null) { reader.close(); } return jsonArray; } } return jsonArray; } }