Zip4j比jdk自带的zip类的好处是支持密码,操作更加简单,而且只要导入1个jar,不依赖于其他类库,所以使用非常方便:
1.最简单的方式压缩一堆文件到zip里:
try { // Initiate ZipFile object with the path/name of the zip file. // Zip file may not necessarily exist. If zip file exists, then // all these files are added to the zip file. If zip file does not // exist, then a new zip file is created with the files mentioned ZipFile zipFile = new ZipFile("c:\\ZipTest\\AddFilesDeflateComp.zip"); // Build the list of files to be added in the array list // Objects of type File have to be added to the ArrayList 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 Zip Parameters which define various properties such // as compression method, etc. More parameters are explained in other // examples ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression // 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); // Now add files to the zip file // Note: To add a single file, the method addFile can be used // Note: If the zip file already exists and if this zip file is a split file // then this method throws an exception as Zip Format Specification does not // allow updating split zip files zipFile.addFiles(filesToAdd, parameters); } catch (ZipException e) { e.printStackTrace(); }
2.在zip中添加文件夹,把文件压缩到里面:
try { ZipFile zipFile = new ZipFile("c:\\ZipTest\\AddFilesDeflateComp.zip"); 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")); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Sets the folder in the zip file to which these new files will be added. // In this example, test2 is the folder to which these files will be added. // Another example: if files were to be added to a directory test2/test3, then // below statement should be parameters.setRootFolderInZip("test2/test3/"); parameters.setRootFolderInZip("test2/"); // Now add files to the zip file zipFile.addFiles(filesToAdd, parameters); } catch (ZipException e) { e.printStackTrace(); }
3.给压缩文件加密码:
// Set the encryption flag to true // If this is set to false, then the rest of encryption properties are ignored parameters.setEncryptFiles(true); // Set the encryption method to AES Zip Encryption parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); // Set AES Key strength. Key strengths available for AES encryption are: // AES_STRENGTH_128 - For both encryption and decryption // AES_STRENGTH_192 - For decryption only // AES_STRENGTH_256 - For both encryption and decryption // Key strength 192 cannot be used for encryption. But if a zip file already has a // file encrypted with key strength of 192, then Zip4j can decrypt this file parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); // Set password parameters.setPassword("test123!"); // Now add files to the zip file // Note: To add a single file, the method addFile can be used // Note: If the zip file already exists and if this zip file is a split file // then this method throws an exception as Zip Format Specification does not // allow updating split zip files zipFile.addFiles(filesToAdd, parameters);
可以通过语句
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
设置不同的加密算法。
4.将文件夹以及里面所有文件/文件夹添加到zip中:
try { // Initiate ZipFile object with the path/name of the zip file. ZipFile zipFile = new ZipFile("c:\\ZipTest\\AddFolder.zip"); // Folder to add String folderToAdd = "c:\\FolderToAdd"; // Initiate Zip Parameters which define various properties such // as compression method, etc. ZipParameters parameters = new ZipParameters(); // set compression method to store compression parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // Set the compression level parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Add folder to the zip file zipFile.addFolder(folderToAdd, parameters); } catch (ZipException e) { e.printStackTrace(); }这个方法简单又实用。
5.将流压缩到zip中:
InputStream is = null; try { ZipFile zipFile = new ZipFile("c:\\ZipTest\\AddStreamToZip.zip"); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // below two parameters have to be set for adding content to a zip file // directly from a stream // this would be the name of the file for this entry in the zip file parameters.setFileNameInZip("yourfilename.txt"); // we set this flag to true. If this flag is true, Zip4j identifies that // the data will not be from a file but directly from a stream parameters.setSourceExternalStream(true); // For this example I use a FileInputStream but in practise this can be // any inputstream is = new FileInputStream("filetoadd.txt"); // Creates a new entry in the zip file and adds the content to the zip file zipFile.addStream(is, parameters); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } }6.压缩成多个分卷:
try{ ZipFile zipFile = new ZipFile("./iam.zip"); ZipParameters parameters = new ZipParameters(); zipFile.createZipFile(new File("Alec Finn - The Water Is Wide.mp3"), parameters,true, 65537); }catch (Exception e) { e.printStackTrace(); }
7.从文件创建压缩分卷:
try { // Initiate ZipFile object with the path/name of the zip file. ZipFile zipFile = new ZipFile("c:\\ZipTest\\CreateSplitZipFileFromFolder.zip"); // Initiate Zip Parameters which define various properties such // as compression method, etc. ZipParameters parameters = new ZipParameters(); // set compression method to store compression parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // Set the compression level. This value has to be in between 0 to 9 parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Create a split file by setting splitArchive parameter to true // and specifying the splitLength. SplitLenth has to be greater than // 65536 bytes // Please note: If the zip file already exists, then this method throws an // exception zipFile.createZipFileFromFolder("C:\\ZipTest", parameters, true, 10485760); } catch (ZipException e) { e.printStackTrace(); }8.从输出流创建zip文件:
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("c:\\ZipTest\\CreateZipFileWithOutputStreams.zip"))); // 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(); } } }9.解压所有文件:
try { // Initiate ZipFile object with the path/name of the zip file. ZipFile zipFile = new ZipFile("c:\\ZipTest\\ExtractAllFiles.zip"); // Extracts all files to the path specified zipFile.extractAll("c:\\ZipTest"); } catch (ZipException e) { e.printStackTrace(); }10.解压单个文件:
try { // Initiate ZipFile object with the path/name of the zip file. ZipFile zipFile = new ZipFile("c:\\ZipTest\\ExtractSingleFile.zip"); // Check to see if the zip file is password protected if (zipFile.isEncrypted()) { // if yes, then set the password for the zip file zipFile.setPassword("test123!"); } // Specify the file name which has to be extracted and the path to which // this file has to be extracted zipFile.extractFile("Ronan_Keating_-_In_This_Life.mp3", "c:\\ZipTest\\"); // Note that the file name is the relative file name in the zip file. // For example if the zip file contains a file "mysong.mp3" in a folder // "FolderToAdd", then extraction of this file can be done as below: zipFile.extractFile("FolderToAdd\\myvideo.avi", "c:\\ZipTest\\"); } catch (ZipException e) { e.printStackTrace(); }例子来源于Zip4j,展开附件可以看到更多实例和源码。