`

Zip 压缩和解压缩

阅读更多
要依赖
ant.1.7.0.jar

<dependency>
	<groupId>ant</groupId>
	<artifactId>ant</artifactId>
	<version>1.7.0</version>
	<exclusions>
		<exclusion>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant-launcher</artifactId>
		</exclusion>
	</exclusions>
</dependency>


import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

/**
 * ZIP格式文件压缩/解压工具类
 * 
 * @author 应卓
 *
 */
public final class ZipUtils {

	/**
	 * 私有构造方法
	 */
	private ZipUtils() {
		super();
	}

	/**
	 * 压缩zip文件
	 * 
	 * @param directory 压缩目录
	 * @param dest 压缩后的zip文件
	 * @param encoding 字符编码
	 */
	public static void compress(File directory, File dest, String encoding) {
		compress(directory, dest, encoding, null, null);
	}

	/**
	 * 压缩zip文件
	 * 
	 * @param directory 压缩目录
	 * @param dest 压缩后的zip文件
	 * @param encoding 字符编码
	 * @param includes 包含表达式(ant风格,逗号分隔)
	 * @param excludes 排除表达式(ant风格,逗号分隔)
	 */
	public static void compress(File directory, File dest, String encoding, String includes, String excludes) {
		if (directory == null) {
			throw new NullPointerException("'directory' must not be null");
		}
		
		if (! directory.exists()) {
			throw new IllegalArgumentException("'directory' dose not exists");
		}
		
		if (directory.isFile()) {
			throw new IllegalArgumentException("'directory' is not a directory'");
		}
		
		if (dest == null) {
			throw new NullPointerException("'dest' must not be null");
		}
		
		if (dest.isDirectory()) {
			throw new IllegalArgumentException("'dest' is not a file'");
		}
		
		Project project = new Project();
		Zip zip = new Zip();
		zip.setEncoding(encoding);
		zip.setProject(project);
		zip.setDestFile(dest);
		
		FileSet fileSet = new FileSet();
		fileSet.setProject(project);
		fileSet.setDir(directory);
		
		if (null != includes) {
			fileSet.setIncludes(includes);
		}
		
		if (null != excludes) {
			fileSet.setExcludes(excludes);
		}
		
		zip.addFileset(fileSet);
		zip.execute();
	}
}
分享到:
评论
2 楼 yingzhor 2012-05-23  
呵呵。 是啊。 JDK的zip工具包有bug的,好像。
1 楼 wait8712 2012-05-23  
我最常用的是org.apache.tools.zip.*这里面的包,最主要的是还能解决乱码,共勉之

相关推荐

Global site tag (gtag.js) - Google Analytics