首页 > 代码库 > java zip压缩和解压(支持中文)
java zip压缩和解压(支持中文)
package com.xeon.mis.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.zip.Adler32; import java.util.zip.CheckedOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; /** * 多文件压缩 * */ public class ZipUtils { public static void zipCompress(List<String> srcFiles, String desFile) throws Exception { FileOutputStream outfile = new FileOutputStream(desFile); CheckedOutputStream checkoutput = new CheckedOutputStream(outfile, new Adler32()); BufferedOutputStream out = new BufferedOutputStream(checkoutput); ZipOutputStream zos = new ZipOutputStream(out); // 乱码解决 zos.setEncoding("gbk"); for (String infile : srcFiles) { System.out.println("Writing file " + infile); BufferedInputStream bin = new BufferedInputStream( new FileInputStream(new File(infile))); infile = infile.substring(infile.lastIndexOf("\\") + 1); zos.putNextEntry(new ZipEntry(infile)); byte[] c = new byte[1024]; while ((bin.read(c)) != -1) { zos.write(c, 0, c.length); } bin.close(); zos.closeEntry(); } zos.close(); out.close(); checkoutput.close(); } public static void unzip(String srcFile, String destFile) throws Exception { if (!(srcFile != null && srcFile.endsWith(".zip"))) { throw new Exception("解压文件必须以.zip结尾"); } ZipFile zipFile = new ZipFile(srcFile, "gbk"); Enumeration<ZipEntry> entrys = zipFile.getEntries(); while (entrys.hasMoreElements()) { ZipEntry zipEntry = entrys.nextElement(); String name = zipEntry.getName(); System.out.println("====" + name); // 跳过目录 if (name.endsWith("/")) { continue; } InputStream in = zipFile.getInputStream(zipEntry); BufferedInputStream bufferedinput = new BufferedInputStream(in); byte[] b = new byte[1024]; File file = new File(destFile + name); File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } BufferedOutputStream bufferedoutput = new BufferedOutputStream( new FileOutputStream(file)); while ((bufferedinput.read(b)) > 0) { bufferedoutput.write(b, 0, b.length); } bufferedoutput.close(); in.close(); } } public static void main(String[] args) throws Exception { unzip("j:\\test\\1.zip", "j:\\test\\"); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。