因为压缩包内的文件需要用到中文命名,如果用jdk自带的zip Jar包没法实现,如果以中文命名会直接不显示,因此采用了
commons.compress.jar。
public static Boolean generateZip(List<Map<String,Object>> bytes) throws Exception { //ZipOutputStream out = null; Boolean flag = true; //压缩文件路径 String strZipName = "C:/QueryResult.zip"; File desFile = new File(strZipName); if(!desFile.exists()) { desFile.getParentFile().mkdirs(); desFile.createNewFile(); } ZipArchiveOutputStream zous = new ZipArchiveOutputStream(desFile); //防止中文乱码 if(zous instanceof ZipArchiveOutputStream) { zous.setEncoding("GBK"); } try { zous.setUseZip64(Zip64Mode.AsNeeded); //out = new ZipOutputStream(new FileOutputStream(strZipName)); for (int i=0;i<bytes.size();i++) { int xh = i+1; String time = (String) bytes.get(i).get("time"); String name = (String) bytes.get(i).get("name"); String zjh = (String) bytes.get(i).get("zjh"); //前面几个参数只是为了命名文件,这个by才是二进制文件,是byte[]的形式。 byte[] by = (byte[]) bytes.get(i).get("buffer"); String filename = xh+"-"+time+"-"+name+"-"+zjh+".pdf"; ArchiveEntry entry = new ZipArchiveEntry(filename); zous.putArchiveEntry(entry); zous.write(by); zous.closeArchiveEntry(); // out.putNextEntry(new ZipEntry(xh+"-"+time+"-"+name+"-"+zjh+".pdf")); // out.write(by); // out.flush(); // out.closeEntry(); } } catch (Exception e) { flag = false; e.printStackTrace(); } finally { // if (out != null) { // out.close(); // } zous.close(); return flag; } }