zip压缩unzip解压缩
package com.health.synergism.base.util; import org.apache.commons.codec.binary.Base64; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * @author Bai Jing on 2021-05-08 */ public class StreamUtil { /** * ZIP压缩XML数据,文件内容BASE64编码 * * @param fileName * @return * @throws Exception */ public static String file2Str(String fileName) throws Exception { byte[] bytes; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(5 * 1024 * 1024); ZipOutputStream zos = new ZipOutputStream(bos)) { InputStream is = StreamUtil.class.getResourceAsStream(fileName); if (is.available() > 0) { try (BufferedInputStream fileReader = new BufferedInputStream(is)) { zos.putNextEntry(new ZipEntry(fileName)); byte[] b = new byte[1024]; int i; while ((i = fileReader.read(b)) != -1) { zos.write(b, 0, i); } zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } bytes = bos.toByteArray(); } return Base64.encodeBase64String(bytes); } /** * 文件内容BASE64解码,UNZIP解压缩 * * @param con * @throws Exception */ public static void str2File(String con) throws Exception { byte[] bytes = Base64.decodeBase64(con); try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ZipInputStream zis = new ZipInputStream(bis)) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); try (FileOutputStream fos = new FileOutputStream("D:\\xml\\" + name)) { byte[] buf = new byte[1024]; int len; while ((len = zis.read(buf)) != -1) { fos.write(buf, 0, len); } zis.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } } } public static void main(String[] args) throws Exception { String s = file2Str("/2015.xml"); System.out.println(s); str2File(s); } }