package cn.zip;//压缩
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;
public class MyZip { private void zip(String zipFileName, File inputFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); zip(out, inputFile, ""); System.out.println("压缩中......"); out.close();
}
private void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); out.putNextEntry(new ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i]); } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(base); int b; System.out.println(base); while ((b = in.read()) != -1) { out.write(b); } in.close(); } }public static void main(String[] args) { MyZip book=new MyZip(); try { book.zip("F:\\123.zip", new File("F:\\123")); System.out.println("压缩完成!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }}}/***解压*/package cn.zip;
import java.io.File;import java.io.FileInputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;
public class Decompressing { public static void main(String[] args) { ZipInputStream zin; try { zin = new ZipInputStream(new FileInputStream("f://123.zip"));
ZipEntry entry = zin.getNextEntry();
while (((entry = zin.getNextEntry()) != null) && !entry.isDirectory()) { File file = new File("f://123" + entry.getName()); System.out.println(file); if(!file.exists()){ file.mkdirs(); file.createNewFile(); } zin.closeEntry(); System.out.println(entry.getName()+"解压成功"); }zin.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}