首页 > 编程语言 > 详细

java压缩和解压文件

时间:2014-12-31 02:04:43      阅读:364      评论:0      收藏:0      [点我收藏+]
package hhf.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 压缩文件、解压压缩文件
 * @author HHF 
 * 2014年12月30日
 */
public class ZIP {

	/**
	 * 功能:压缩多个文件成一个zip文件
	 * @param srcfile:源文件列表
	 * @param zipfile:压缩后的文件
	 */
	public static void zipFiles(File[] srcfile, File zipfile) {
		byte[] buf = new byte[1024];
		try {
			// ZipOutputStream类:完成文件或文件夹的压缩
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
			for (int i = 0; i < srcfile.length; i++) {
				FileInputStream in = new FileInputStream(srcfile[i]);
				out.putNextEntry(new ZipEntry(srcfile[i].getName()));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
			out.close();
			System.out.println("压缩完成.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 功能:解压缩
	 * @param zipfile:需要解压缩的文件
	 * @param descDir:解压后的目标目录
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(File zipfile, String descDir) {
		File file = new File(descDir);
		if (!file.exists()) {
			try {
				file.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			ZipFile zf = new ZipFile(zipfile);
			for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				String zipEntryName = entry.getName();
				InputStream in = zf.getInputStream(entry);
				OutputStream out = new FileOutputStream(descDir + zipEntryName);
				byte[] buf1 = new byte[1024];
				int len;
				while ((len = in.read(buf1)) > 0) {
					out.write(buf1, 0, len);
				}
				in.close();
				out.close();
				System.out.println("解压缩完成.");
			}

			zf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// 需要解压缩的文件
		File file = new File("D:\\test");
		File filenew = new File("D:\\test.zip");
		zipFiles(file.listFiles(), filenew);

		// 解压后的目标目录
		String dir = "D:\\workspace\\";
		unZipFiles(filenew, dir);
	}
}

? ? 旨在大家需要的时候方便作为工具类使用

java压缩和解压文件

原文:http://java--hhf.iteye.com/blog/2171329

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!