`
hzy3774
  • 浏览: 984421 次
  • 性别: 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 java常用工具类iceroot开源类库.zip

    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开源包6

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

    java开源包10

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

    java开源包9

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

    java开源包8

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

    java开源包4

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

    java开源包11

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

    java开源包5

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

    java开源包1

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

    java开源包3

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

    java开源包101

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

    javacsv类库cb4j.zip

    csv batch for java 是一个java批量处理csv的类库.旨在简化csv文件的批量处理. cb4j解决常见的如读取,解析和验证csv所记录的繁琐工作,让你专注于批量处理的业务逻辑. 标签:cb4j

    JAVA上百实例源码以及开源项目

     Java zip压缩包查看程序,应用弹出文件选择框,选择ZIP格式的压缩文件,可以像Winrar软件一样查看压缩文件内部的文件及文件夹,源码截图如上所示。 Java 数字签名、数字证书生成源码 2个目标文件 摘要:JAVA源码,...

    java开源包2

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

    java开源包7

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

    详解C#压缩、解压文件夹/文件(带密码)

    DotNetZip是一个开源的免费类库,主要提供了快速操作zip文件的工具集,VB、C#任何.Net语言都可以通过它创建、解压缩zip文件。我使用该类库最主要的目的还是因为它可以创建带密码保护的压缩文件。 只有设置了zip....

    Java图片处理类库SimpleImage.zip

    SimpleImage是阿里巴巴的一个Java图片处理的类库,可以实现图片缩略、水印等处理。 SimpleImage中的ImageRender是图片处理的基类,它是一个抽象类,我们看到,该类中定义了一个抽象方法render(),同时持有一个对...

    JAVA上百实例源码以及开源项目源代码

     Java zip压缩包查看程序,应用弹出文件选择框,选择ZIP格式的压缩文件,可以像Winrar软件一样查看压缩文件内部的文件及文件夹,源码截图如上所示。 Java 数字签名、数字证书生成源码 2个目标文件 摘要:JAVA源码,...

    2个G的java实例源码以及开源项目源码

    2个G的java实例源码以及开源项目源码,源码难易程度分为初级... zip Java 实现的 EverBox 库Everbox4j. zip Java 数据库连接池 BoneCPjar Java 注册表操作类 jared . tgz Java 转 C ++代码工具J2C. jar OAuth 实现...

Global site tag (gtag.js) - Google Analytics