使用ant实现zip压缩和解压缩(一)

压缩文件的方法有很多种,最常用的是用util工具和ant工具.两者的区别是:util工具不能设置文件的编码格式,而ant工具可以自定义文件编码.
下面通过ant工具进行压缩和解压缩的

1.首先看压缩过程,直接看代码:ZipUtil.

<span style="font-size:12px;">package com.ilucky.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * @author IluckySi
 * @date 20140531
 */
public class ZipUtil {

	public String code;
	
	public int buffer;
	
	public String srcPath;
	
	public String dstPath;
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getBuffer() {
		return buffer;
	}

	public void setBuffer(int buffer) {
		this.buffer = buffer;
	}
	
	public String getSrcPath() {
		return srcPath;
	}

	public void setSrcPath(String srcPath) {
		
		this.srcPath = srcPath;
	}

	public String getDstPath() {
		return dstPath;
	}

	public void setDstPath(String dstPath) {
		this.dstPath = dstPath;
	}
	
	public void startZip () {
		boolean next = true;
		if(new File(srcPath).exists() == false) {
			try {
				next = false;
				throw new Exception("源路径 " + srcPath + "不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String dstDir = dstPath.substring(0, dstPath.lastIndexOf("/"));
		if(new File(dstDir).exists() == false) {
			try {
				next = false;
				throw new Exception("目标路径" + dstDir + "不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(next == false) {
			return;
		}
		File zip = null;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		ZipOutputStream zos = null;
		try {
			zip = new File(dstPath);
			fos = new FileOutputStream(zip);
			bos = new BufferedOutputStream(fos);
			zos = new ZipOutputStream(bos);
			zos.setEncoding(code);
			generateZip(srcPath, zos);
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				if(zos != null) {
					zos.closeEntry();
					zos.close();
					zos = null;
				} 
				if(bos != null) {
					bos.close();
					bos = null;
				}
				if(fos != null) {
					fos.close();
					fos = null;
				}
			} catch (IOException e) {
				System.out.println(e.toString());
			}
		}
	}
	
	public void generateZip(String filePath, ZipOutputStream zos) {
		File file = new File(filePath);
		File[] files = null;
		try {
			if (file.isDirectory()) {
				files = file.listFiles();
			} else if (file.isFile()) {
				files = new File[1];
				files[0] = file;
			}
			for (int i = 0; files != null && i < files.length; i++) {
				//关键:zip节点文件名称.
				String fileName =  files[i].getPath().substring(srcPath.lastIndexOf("/") + 1);
				if (files[i].isDirectory()) {
					System.out.println("开始压缩目录" + files[i].getPath());
					zos.putNextEntry(new ZipEntry(fileName + "/"));
					generateZip(files[i].getPath(), zos);
				} else {
					FileInputStream fis = null;
					BufferedInputStream bis = null;
					try {
						System.out.println("开始压缩文件" + files[i].getPath());
						zos.putNextEntry(new ZipEntry(fileName));
						fis = new FileInputStream(files[i]);
						bis = new BufferedInputStream(fis);
						byte[] bytes = new byte[buffer];
						int length = 0;
						while ((length = bis.read(bytes, 0, buffer)) != -1) {
							zos.write(bytes, 0, length);
							zos.flush();
						}
					} catch (Exception e) {
						System.out.println(e.toString());
					} finally {
						try {
							if(bis != null) {
								bis.close();
								bis = null;
							}
							if(fis != null) {
								fis.close();
								fis = null;
							}
						} catch (IOException e) {
							System.out.println(e.toString());
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}
</span>

  在压缩过程中,关键之处是获取压缩文件的节点名称,files[i].getPath().substring(srcPath.lastIndexOf("/") + 1),即lastIndexOf的使用.
  其次是设置编码格式为GB2312,否则会出现中文乱码.

2.然后看解压缩过程,直接看代码:UnZipUtil.

<span style="font-size:12px;">package com.ilucky.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

/**
 * @author IluckySi
 * @date 20140531
 */
public class UnZipUtil {

public String code;
	 
	public int buffer;
	
	public String srcPath;
	
	public String dstPath;
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getBuffer() {
		return buffer;
	}

	public void setBuffer(int buffer) {
		this.buffer = buffer;
	}
	
	public String getSrcPath() {
		return srcPath;
	}

	public void setSrcPath(String srcPath) {
		
		this.srcPath = srcPath;
	}

	public String getDstPath() {
		return dstPath;
	}

	public void setDstPath(String dstPath) {
		this.dstPath = dstPath;
	}
	
	@SuppressWarnings("rawtypes")
	public void startUnZip () {
		boolean next = true;
		if(new File(srcPath).exists() == false) {
			try {
				next = false;
				throw new Exception("源路径 " + srcPath + "不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(new File(dstPath).exists() == false) {
			try {
				next = false;
				throw new Exception("目标路径" + dstPath + "不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(next == false) {
			return;
		}
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(srcPath, code); 
			Enumeration emu = zipFile.getEntries();
			while(emu.hasMoreElements()) {
				InputStream is = null;
				BufferedInputStream bis = null;
				FileOutputStream fos = null;
				BufferedOutputStream bos = null;
				try {
					ZipEntry entry = (ZipEntry) emu.nextElement();
					if(!entry.isDirectory()) {
						File file = new File(dstPath + "/" + entry.getName());
						System.out.println("开始创建解压缩文件" + file.getPath());
						is = zipFile.getInputStream(entry);
						bis = new BufferedInputStream(is);
						//关键:创建父文件,mkdirs是创建多层目录.
						File parent = file.getParentFile();
						if (parent != null && (!parent.exists())) {
							parent.mkdirs();
							System.out.println("开始创建解压缩目录" + parent.getPath());
						}
						fos = new FileOutputStream(file);
						bos = new BufferedOutputStream(fos, buffer);
						byte[] buf = new byte[buffer];
						int length = 0;
						while ((length = bis.read(buf, 0, buffer)) != -1) {
							bos.write(buf, 0, length);
							bos.flush();
						}
					}
				} catch (Exception e) {
					System.out.println(e.toString());
				} finally {
					try {
						if(bos != null) {
							bos.close();
							bos = null;
						}
						if(fos != null) {
							fos.close();
							fos = null;
						}
						if(bis != null) {
							bis.close();
							bis = null;
						}
						if(is != null) {
							is.close();
							is = null;
						}
					} catch (IOException e) {
						System.out.println(e.toString());
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}</span>

  在解压缩过程中,关键之处是如何创建多层目录,即mkdir(创建一层目录)和mkdirs(创建多层目录)的区别.
  其次是设置编码格式为GB2312,否则会出现中文乱码.

3.最后通过测试程序对压缩过程和解压缩过程进行验证.直接看代码:MainTest.

<span style="font-size:12px;">package com.ilucky.zip;

/**
 * @author IluckySi
 * @date 20140531
 */
public class MainTest {

	public static void main(String[] args) {
		
		//将某目录下的某目录/文件压缩到指定的某目录下.
		ZipUtil zipUtil = new ZipUtil();
		zipUtil.setCode("GB2312");
		zipUtil.setBuffer(10240);
		zipUtil.setSrcPath("E:/src/src");//如果是文件必须带后缀.
		zipUtil.setDstPath("E:/dst/src.zip");
		long startZip = System.currentTimeMillis();
		//zipUtil.startZip();
		long endZip = System.currentTimeMillis();
		System.out.println("压缩文件耗时: " + (endZip - startZip) + "毫秒");
		
		//将某目录下的某压缩文件解压缩到指定的某目录下.
		UnZipUtil unZipUtil = new UnZipUtil();
		unZipUtil.setCode("GB2312");
		unZipUtil.setBuffer(10240);
		unZipUtil.setSrcPath("E:/src/src.zip");
		unZipUtil.setDstPath("E:/dst");
		long startUnZip = System.currentTimeMillis();
		unZipUtil.startUnZip();
		long endUnZip = System.currentTimeMillis();
		System.out.println("解压缩文件耗时: " + (endUnZip - startUnZip) + "毫秒");
	}
}
</span>
  在测试过程中源路径和目的路径都要是通过正斜线分割,否则会有问题.

点击链接下载源码和ant.jar
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值