这就不多说废话了,代码注释很清晰,直接可以运行的;
public static void main(String[] args) { // TODO Auto-generated method stub try { zip("E:\\files\\shopImage\\1234.zip", new File("E:\\files\\shopImage\\1234")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //1.要压缩的zip文件路径(目标文件)2.被压缩的文件路径(源文件路径) private static void zip(String zipFileName, File inputFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream( zipFileName));//创建zip输出流 BufferedOutputStream bo = new BufferedOutputStream(out); zip(out, inputFile, inputFile.getName(), bo); bo.close(); out.close(); // 输出流关闭 System.out.println("压缩完成"); } private static void zip(ZipOutputStream out, File f, String base, BufferedOutputStream bo) throws Exception { // 方法重载 if (f.isDirectory()) {//如果是文件夹的话 File[] fl = f.listFiles(); if (fl.length == 0) {//空文件夹压缩 out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base System.out.println(base + "/"); } int k = 0; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹 } System.out.println("第" + k + "次递归"); k++; } else {//压缩文件 out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base System.out.println(base); FileInputStream in = new FileInputStream(f); BufferedInputStream bi = new BufferedInputStream(in); int b; while ((b = bi.read()) != -1) { bo.write(b); // 将字节流写入当前zip目录 } bi.close(); in.close(); // 输入流关闭 } }