package org; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class Zip { public static void zip(String zipFileName, String inputFile) throws Exception { File f = new File(inputFile); ZipOutputStream out = new ZipOutputStream(new FileOutputStream( zipFileName)); zip(out, f, null); System.out.println("zip done"); out.close(); } private static void zip(ZipOutputStream out, File f, String base) throws Exception { System.out.println("zipping " + f.getAbsolutePath()); if (f != null && f.isDirectory()) { File[] fc = f.listFiles(); if (base != null) out.putNextEntry(new ZipEntry(base + "/")); base = base == null ? "" : base + "/"; for (int i = 0; i < fc.length; i++) { zip(out, fc[i], base + fc[i].getName()); } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; while ((b = in.read()) != -1) out.write(b); in.close(); } } public static void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { String name = z.getName(); if (z.isDirectory()) { name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("MD " + outputDirectory + File.separator + name); } else { System.out.println("unziping " + z.getName()); File f = new File(outputDirectory + File.separator + name); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); } public void deleteFolder(File dir) { File filelist[] = dir.listFiles(); int listlen = filelist.length; for (int i = 0; i < listlen; i++) { if (filelist[i].isDirectory()) { deleteFolder(filelist[i]); } else { filelist[i].delete(); } } dir.delete(); } /** * Test ZIP/UNZIP * @param args */ public static void main(String[] args) { try { Zip t = new Zip(); t.zip("c:\\test.zip","c:\\test"); //在c盘要自己提前建立test文件夹 // t.unzip("c:\\test.zip","c:\\test"); File file = new File("c:\\test"); t.deleteFolder(file); } catch (Exception e) { e.printStackTrace(System.out); } } }
Java实现Zip压缩,解压缩(一)
猜你喜欢
转载自hechuanzhen.iteye.com/blog/1726036
今日推荐
周排行