/** * 创建zip文件 使用文件列表 * * @param zipfileName * @param filesToAdd */ public static void CreateZipWithFilelist(String zipfileName, ArrayList<File> filesToAdd) { // Input and OutputStreams are defined outside of the try/catch block // to use them in the finally block ZipOutputStream outputStream = null; InputStream inputStream = null; try { // Prepare the files to be added // ArrayList filesToAdd = new ArrayList(); // filesToAdd.add(new File("c:\\ZipTest\\sample.txt")); // filesToAdd.add(new File("c:\\ZipTest\\myvideo.avi")); // filesToAdd.add(new File("c:\\ZipTest\\mysong.mp3")); // Initiate output stream with the path/file of the zip file // Please note that ZipOutputStream will overwrite zip file if it // already exists outputStream = new ZipOutputStream(new FileOutputStream(new File(zipfileName))); // Initiate Zip Parameters which define various properties such // as compression method, etc. More parameters are explained in // other // examples ZipParameters parameters = new ZipParameters(); // Deflate compression or store(no compression) can be set below parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // Set the compression level. This value has to be in between 0 to 9 // Several predefined compression levels are available // DEFLATE_LEVEL_FASTEST - Lowest compression level but higher speed // of compression // DEFLATE_LEVEL_FAST - Low compression level but higher speed of // compression // DEFLATE_LEVEL_NORMAL - Optimal balance between compression // level/speed // DEFLATE_LEVEL_MAXIMUM - High compression level with a compromise // of speed // DEFLATE_LEVEL_ULTRA - Highest compression level but low speed parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // This flag defines if the files have to be encrypted. // If this flag is set to false, setEncryptionMethod, as described // below, // will be ignored and the files won't be encrypted parameters.setEncryptFiles(true); // Zip4j supports AES or Standard Zip Encryption (also called // ZipCrypto) // If you choose to use Standard Zip Encryption, please have a look // at example // as some additional steps need to be done while using // ZipOutputStreams with // Standard Zip Encryption parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); // If AES encryption is used, this defines the key strength parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); // self descriptive parameters.setPassword("YourPassword"); // Now we loop through each file and read this file with an // inputstream // and write it to the ZipOutputStream. for (int i = 0; i < filesToAdd.size(); i++) { File file = (File) filesToAdd.get(i); // This will initiate ZipOutputStream to include the file // with the input parameters outputStream.putNextEntry(file, parameters); // If this file is a directory, then no further processing is // required // and we close the entry (Please note that we do not close the // outputstream yet) if (file.isDirectory()) { outputStream.closeEntry(); continue; } // Initialize inputstream inputStream = new FileInputStream(file); byte[] readBuff = new byte[4096]; int readLen = -1; // Read the file content and write it to the OutputStream while ((readLen = inputStream.read(readBuff)) != -1) { outputStream.write(readBuff, 0, readLen); } // Once the content of the file is copied, this entry to the zip // file // needs to be closed. ZipOutputStream updates necessary header // information // for this file in this step outputStream.closeEntry(); inputStream.close(); } // ZipOutputStream now writes zip header information to the zip file outputStream.finish(); } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static ByteArrayOutputStream requestsToZip( ServletContext context, String globalTitle, Date generationDate, ScrambleRequest[] scrambleRequests, String password, String generationUrl) throws IOException, DocumentException, ZipException { ByteArrayOutputStream baosZip = new ByteArrayOutputStream(); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); if (password != null) { parameters.setEncryptFiles(true); parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); parameters.setPassword(password); } parameters.setSourceExternalStream(true); ZipOutputStream zipOut = new ZipOutputStream(baosZip); HashMap<String, Boolean> seenTitles = new HashMap<String, Boolean>(); for (ScrambleRequest scrambleRequest : scrambleRequests) { String safeTitle = toFileSafeString(scrambleRequest.title); int salt = 0; String tempNewSafeTitle = safeTitle; while (seenTitles.get(tempNewSafeTitle) != null) { tempNewSafeTitle = safeTitle + " (" + (++salt) + ")"; } safeTitle = tempNewSafeTitle; seenTitles.put(safeTitle, true); String pdfFileName = "pdf/" + safeTitle + ".pdf"; parameters.setFileNameInZip(pdfFileName); zipOut.putNextEntry(null, parameters); PdfReader pdfReader = createPdf(globalTitle, generationDate, scrambleRequest); byte[] b = new byte[(int) pdfReader.getFileLength()]; pdfReader.getSafeFile().readFully(b); zipOut.write(b); zipOut.closeEntry(); String txtFileName = "txt/" + safeTitle + ".txt"; parameters.setFileNameInZip(txtFileName); zipOut.putNextEntry(null, parameters); zipOut.write(join(stripNewlines(scrambleRequest.getAllScrambles()), "\r\n").getBytes()); zipOut.closeEntry(); } String safeGlobalTitle = toFileSafeString(globalTitle); String jsonFileName = safeGlobalTitle + ".json"; parameters.setFileNameInZip(jsonFileName); zipOut.putNextEntry(null, parameters); HashMap<String, Object> jsonObj = new HashMap<String, Object>(); jsonObj.put("sheets", scrambleRequests); jsonObj.put("competitionName", globalTitle); jsonObj.put("version", Utils.getProjectName() + "-" + Utils.getVersion()); jsonObj.put("generationDate", generationDate); jsonObj.put("generationUrl", generationUrl); String json = GSON.toJson(jsonObj); zipOut.write(json.getBytes()); zipOut.closeEntry(); String jsonpFileName = safeGlobalTitle + ".jsonp"; parameters.setFileNameInZip(jsonpFileName); zipOut.putNextEntry(null, parameters); String jsonp = "var SCRAMBLES_JSON = " + json + ";"; zipOut.write(jsonp.getBytes()); zipOut.closeEntry(); parameters.setFileNameInZip(safeGlobalTitle + ".html"); zipOut.putNextEntry(null, parameters); InputStream is = context.getResourceAsStream(HTML_SCRAMBLE_VIEWER); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { line = line.replaceAll("%SCRAMBLES_JSONP_FILENAME%", jsonpFileName); sb.append(line).append("\n"); } zipOut.write(sb.toString().getBytes()); zipOut.closeEntry(); parameters.setFileNameInZip(safeGlobalTitle + ".pdf"); zipOut.putNextEntry(null, parameters); // Note that we're not passing the password into this function. It seems pretty silly // to put a password protected pdf inside of a password protected zip file. ByteArrayOutputStream baos = requestsToPdf(globalTitle, generationDate, scrambleRequests, null); zipOut.write(baos.toByteArray()); zipOut.closeEntry(); zipOut.finish(); zipOut.close(); return baosZip; }