public static void main(String[] args) throws IOException { String path = "F:\HTML\PAY"; String zipFile = "F:\HTML\PAY\zip_"+System.currentTimeMillis()+".zip"; File dictionary = new File(path); File[] listFiles = dictionary.listFiles(); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); zip(path,listFiles,zipOut); zipOut.flush(); zipOut.close(); System.out.println("Finished"); } public static void zip(String root,File[] fileList, ZipOutputStream zipOut) throws IOException { ZipEntry ze = null; for (File file : fileList) { if (file.isDirectory()) { zip(root,file.listFiles(), zipOut); } else { // 创建ZipEntry ,设置需加入压缩包的对象名称,为压缩后的文件设置名称 String fileName = file.getParent().replace(root, "")+File.separator+file.getName(); if(fileName.startsWith(File.separator)){ fileName = fileName.substring(1); } System.out.println(fileName); ze = new ZipEntry(fileName); ze.setSize(file.length()); ze.setTime(file.lastModified()); // 每一个被压缩的文件都用ZipEntry表示 zipOut.putNextEntry(ze); FileInputStream fileInputStream = new FileInputStream(file); byte buffer[] = new byte[4096]; for (int n = 0; -1 != (n = fileInputStream.read(buffer));) { zipOut.write(buffer, 0, n); } fileInputStream.close(); } } }