import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.junit.Test; import until.ZipUtil; import java.io.*; import java.util.Enumeration; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2017/9/26 8:36 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class ZipTest { String zipPath = "D:\\mysoft\\data\\zipdepress\\zipdepress.zip";//需要解压的压缩文件 String outPath = "D:\\mysoft\\data\\zipdepress\\";//解压完成后保存路径,记得"\\"结尾哈 @Test public void zipFristDecompessTest(){ try { ZipUtil.zipFristDecompess(zipPath,outPath); } catch (IOException e) { e.printStackTrace(); } } /** * 只能解压一级目录 * * @Author wugong * @Date 2017/9/26 8:58 * @Modify if true,please enter your name or update time * @params */ public static void zipFristDecompess(String zipPath, String outPath) throws IOException { ZipFile zipFile = new ZipFile(zipPath, "GBK");//压缩文件的实列,并设置编码 //获取压缩文中的所以项 for (Enumeration<ZipEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements(); ) { ZipEntry zipEntry = enumeration.nextElement();//获取元素 //排除空文件夹 if (!zipEntry.getName().endsWith(File.separator)) { int lastIndexOf = zipEntry.getName().lastIndexOf("."); int endIndex = lastIndexOf < 0 ? zipEntry.getName().length() : lastIndexOf; //创建解压目录 String outPathFinish = outPath + zipEntry.getName().substring(0, endIndex); File outFile = new File(outPathFinish); //判断是否存在解压目录 if (!outFile.exists()) { outFile.mkdirs(); } OutputStream os = new FileOutputStream(outFile.getPath() + "\\" + zipEntry.getName());//创建解压后的文件 BufferedOutputStream bos = new BufferedOutputStream(os);//带缓的写出流 InputStream is = zipFile.getInputStream(zipEntry);//读取元素 BufferedInputStream bis = new BufferedInputStream(is);//读取流的缓存流 CheckedInputStream cos = new CheckedInputStream(bis, new CRC32());//检查读取流,采用CRC32算法,保证文件的一致性 byte[] b = new byte[1024];//字节数组,每次读取1024个字节 //循环读取压缩文件的值 while (cos.read(b) != -1) { bos.write(b);//写入到新文件 } cos.close(); bis.close(); is.close(); bos.close(); os.close(); } else { //如果为空文件夹,则创建该文件夹 new File(outPath + zipEntry.getName()).mkdirs(); } } System.out.println("解压完成"); zipFile.close(); } }
pom依赖:
<!-- ant --> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.9.7</version> </dependency>
或者网盘下载jar:链接:http://pan.baidu.com/s/1i4I55jv 密码:41gd