添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; * 本工具类解压标准的Zip包到指定目录中 public class UnzipUtility { * 读/写数据时缓冲区大小 private static final int BUFFER_SIZE = 4096; * 解压有zipFilePath所指定的Zip文件到destDirectory所指定的目录(如果目标目录不存在将会重新创建) * @param zipFilePath * @param destDirectory * @throws IOException public void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); // 遍历Zip文件中的条目 while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // 如果条目是文件直接解压 extractFile(zipIn, filePath); } else { // 如果条目是目录, 创建对应的目录 File dir = new File(filePath); dir.mkdir(); zipIn.closeEntry(); entry = zipIn.getNextEntry(); zipIn.close(); * 解压Zip包的条目 (文件条目) * @param zipIn * @param filePath * @throws IOException private void extractFile(ZipInputStream zipIn, String filePath) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); bos.close(); UnzipUtility.java中提供了一个公有的方法用来解压Zip包的:
<span style="font-family:Times New Roman;">unzip(String zipFilePath, String destDirectory)</span>
下面添加一个测试类 UnzipUtilityTest.java : * 一个控制台应用来测试 UnzipUtility 类 <span style="font-family:Times New Roman;">public class UnzipUtilityTest { public static void main(String[] args) { String zipFilePath = "e:/Test/MyPics.zip"; String destDirectory = "f:/Pics"; UnzipUtility unzipper = new UnzipUtility(); try { unzipper.unzip(zipFilePath, destDirectory); } catch (Exception ex) { // 一些错误的产生 ex.printStackTrace(); }</span>