本文主要是介绍java如何解压zip压缩包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教...
java解压zip压缩包
坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,我索性给他写了个 demo ,也顺手记录一下。
实例代码
package com.yuhuofei.utjsils; import java.io.*; import java.nio.charset.Charset; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * @Description * @ClassName UnzipUtils * @Author yuhuofei * @Date 2android022/8/10 21:03 * @Version 1.0 */ public class UnzipUtils { /** * 解压zip压缩文件到指定目录 * * @param zipPath zip压缩文件绝对路径 * @param descDir 指定的解压目录 */ public static void unzipFile(String zipPath, String descDir) throws IOException { try { File zipFile = new File(zipPath); if (!zipFile.exists()) { throw new IOException("要解压的压缩文件不存在"); } File pathFile = new File(descDir); if (!pathFile.exists()) { pathFile.mkdirs(); } InputStream input = new FileInputStream(zipPath); unzipWithStream(input, descDir); } catch (Exception e) { throw new IOException(e); } } /** * 解压 * * @param inputStream * @param descDir */ public static void unzipWithStream(InputStream inputStream, String descDir) { if (!descDir.endsWith(File.separator)) { descDir = descDir + File.separator; } try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("GBK"))) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { China编程 String zipEntryNameStr = zipEntry.getName(); String zipEntryName = zipEntryNameStr; if (zipEntryNameStr.contains("/")) { String str1 www.chinasem.cn= zipEntryNameStr.substring(0, zipEntryNameStr.indexOf("/")); zipEntryName = zipEntryNameStr.substring(str1.length() + 1); } String outPath = (descDir + zipEntryName).replace("\\\\", "/"); File outFile = new File(outPath.substring(0, outPath.lastIndexOf('/'))); if (!outFile.exists()) { outFile.mkdirs(); } if (new File(outPath).isDirectory())php { continue; } writeFile(outPath, zipInputStream); zipInputStream.closeEntry(); } System.out.println("======解压成功======="); } catch (IOException e) { System.out.println("压缩包处理异常,异常信息{}" + e); } } //将流写到文件中 public static void writeFile(String filePath, ZipInputStream zipInputStream) { try (OutputStream outputStream = new FileOutputStream(filePath)) { byte[] bytes = new byte[4096]; int len; while ((len = zipInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } } catch (IOException ex) { System.out.println("解压文件时,写出到文件出错"); } } //测试方法 public static void main(String[] args) throws IOException { String zipPath = "D:/test/测试文件.zip"; String descDir = "D:/test/解压/"; unzipFile(zipPath, descDir); } }
结果如下
总结
这篇关于java如何解压zip压缩包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!