`
hzy3774
  • 浏览: 993114 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

好用java开源zip压缩解压类库Zip4j

 
阅读更多

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,展开附件可以看到更多实例和源码。
  • 大小: 82.4 KB
分享到:
评论
1 楼 wujie_cnhn 2017-04-27  
这个加密压缩后, linux环境下可以解压缩吗

相关推荐

    java常用工具类iceroot开源类库.zip

    在这个压缩包"java常用工具类iceroot开源类库.zip"中,我们可以期待找到Iceroot类库的各种组件和功能。 Iceroot类库的核心目标是简化Java开发中的常见任务,包括但不限于字符串处理、日期时间操作、集合操作、文件...

    android、java、加密解压工具类库

    首先,我们要提到的是一个名为“zip4j”的开源库,它是Java平台上的一个强大的压缩和解压库,同时也支持Android平台。在标题和描述中提及的资源中,我们可以看到`zip4j_1.3.1.jar`,这是zip4j的1.3.1版本的二进制库...

    Java压缩处理类库ZeroTurnaround.zip

    ZeroTurnaround 简称 zt-zip , 是一个 Java 用来处理压缩包的类库。 示例代码: final String prefix = "doc/"; ZipUtil.unpack(new File&#40;"/tmp/demo.zip"&#41;, new File&#40;"/tmp/demo"&#41;, new ...

    基于Java的INI文件操作类库 ini4j.zip

    "基于Java的INI文件操作类库 ini4j.zip" 指的是一款名为`ini4j`的Java类库,专门用于处理INI文件。INI文件是一种常见的配置文件格式,常用于存储软件的设置信息。`ini4j`提供了方便的API,使得在Java应用程序中读写...

    基于java的FTP客户端Java类库 ftp4j.zip

    "基于java的FTP客户端Java类库 ftp4j.zip"就是一个这样的类库,它允许Java程序员轻松地与FTP服务器进行交互,进行文件的上传、下载、删除等操作。 ftp4j是一个开源的Java FTP客户端库,由意大利开发者Marco ...

    java开源包6

    WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...

    c++压缩文件类库

    Zlib是一个广泛使用的开源压缩库,它提供了多种压缩算法,包括DEFLATE,该算法被广泛应用于如ZIP和PNG等文件格式中。在你提到的资源“c++压缩文件类库”中,我们关注的是Zlib库的版本1.2.3,这个版本在C++ Windows...

    java开源包10

    WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...

    java开源包9

    WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...

    基于Java的FTP客户端Java类库 ftp4j.zip

    FTP4j是一个开源的Java库,由Sergio Bossa开发,它提供了丰富的API,使开发者能够轻松地在Java应用程序中集成FTP功能。 ftp4j库的核心特性包括: 1. **连接管理**:ftp4j支持主动和被动模式的FTP连接,以适应不同...

    C#批量压缩文件为zip文件类库.rar

    "C#批量压缩文件为zip文件类库.rar"这个压缩包就提供了一个专门用于批量压缩文件到ZIP格式的类库。 在这个压缩包中,我们可以看到两个主要的文件: 1. **FileCompression.cs**:这是一个C#源代码文件,其中包含了...

    java开源包8

    WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...

    基于java的INI文件操作类库 [ini4j].zip

    `ini4j`是一个专门为Java设计的开源库,允许开发者方便地读取、写入和操作INI文件。这个库的全名是"INI for Java",它提供了一套API,使得在Java程序中处理INI文件变得像操作其他类型的配置文件一样简单。`ini4j`库...

    ECharts - Java类库.zip

    然而,"ECharts - Java 类库.zip" 提到的可能是将 ECharts 集成到 Java 应用程序中的一个工具或框架,以便在服务器端生成 ECharts 图表配置,并将其发送到前端展示。在这个压缩包中,包含的 "ECharts-master" 文件...

    基于java的开源Winzip压缩工具Java版源码.zip

    在给定的资源"基于java的开源Winzip压缩工具Java版源码.zip"中,我们可以深入探讨如何使用Java实现文件压缩功能,类似知名的Winzip工具。这个压缩工具的源码提供了一个很好的学习机会,让我们了解如何在Java中处理...

    java开源包4

    WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...

    unity 解压缩文件zip类库

    首先,"unity 解压缩文件zip类库"指的是Unity中用于处理ZIP文件的库,这通常涉及到第三方库的集成,因为Unity本身并不内置直接解压ZIP文件的功能。一个常见的选择是使用开源库ICSharpCode.SharpZipLib,这个库在...

    C#压缩解压缩类库项目SharpZip.zip

    在这个名为"C#压缩解压缩类库项目SharpZip.zip"的压缩包中,我们很可能会找到一个使用SharpZipLib库来实现C#压缩和解压缩功能的示例项目。 首先,让我们详细了解`SharpZipLib`库。这个库由ICsharpCode提供,它是一...

    基于Java的实例源码-开源Winzip压缩工具Java版源码.zip

    开源Winzip压缩工具的Java版源码是Java技术在实用工具开发领域的体现,它允许开发者利用Java来实现文件的压缩与解压功能,类似于流行的Winzip软件。这个开源项目为学习和理解文件压缩算法以及Java I/O流的使用提供了...

    java源码:FTP客户端Java类库 ftp4j.zip

    在Java编程中,为了方便开发者实现FTP功能,有许多优秀的类库可供选择,其中ftp4j是一个功能强大且易于使用的开源Java FTP客户端库。本文将深入探讨ftp4j的设计理念、核心功能以及如何在实际项目中应用。 ftp4j是由...

Global site tag (gtag.js) - Google Analytics