java对文件压缩和解压

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
/**
 * 使用apache下面的工具包,解决中文乱码
 */
public class Zip {
	

	/**
	 * 获取目录下的所有文件
	 * 
	 * @param dir
	 * @return
	 * @throws FileNotFoundException
	 */
	public static List<File> getFilesByDir(String dir)
			throws FileNotFoundException {
		List<File> fileList = new ArrayList<File>();
		File dirFile = new File(dir);
		if (!dirFile.exists())
			throw new FileNotFoundException(dir + "不存在!");
		for (File file : dirFile.listFiles()) {
			if (file.isDirectory())
				fileList.addAll(getFilesByDir(file.getAbsolutePath()));
			else
				fileList.add(file);
		}
		return fileList;
	}

	/**
	 * 压缩
	 * 
	 * @param dir
	 *            要压缩的目录
	 * @throws Exception
	 */
	public static void zip(String dir) throws Exception {
		FileInputStream fis = null;
		byte[] b = new byte[1024];
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
				new File("c:out.zip")));
		zos.setEncoding("gbk"); // 这里需要设置为gbk,不然要乱码
		zos.setComment("这里设置说明");
		for (File file : getFilesByDir(dir)) {
			zos.putNextEntry(new ZipEntry(file.getName()));
			fis = new FileInputStream(file);
			int len = 0;
			while ((len = fis.read(b)) != -1) {
				zos.write(b, 0, len);
			}
			fis.close();
		}
		zos.flush();
		zos.close();

	}

	/**
	 * 解压
	 * 
	 * @param unZipFilePath
	 *            要解压的文件
	 * @param fileSavePath
	 *            保存路径
	 * @throws Exception
	 */
	public static void unzip(String unZipFilePath, String fileSavePath)
			throws Exception {
		File fileSave = new File(fileSavePath);
		if (!fileSave.exists())
			fileSave.mkdirs();
		File unZipFile = new File(unZipFilePath);
		if (!unZipFile.exists())
			throw new FileNotFoundException(unZipFilePath + "不存在!");
		ZipFile zf = new ZipFile(unZipFile);
		@SuppressWarnings("unchecked")
		Enumeration<ZipEntry> e = zf.getEntries(); // 获取Entrie的枚举
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		byte[] b = new byte[1024];
		while (e.hasMoreElements()) {
			ZipEntry ze = e.nextElement();
			// 如果是个目录
			if (ze.isDirectory()) {
				File f = new File(fileSavePath + File.separator + ze.getName());
				if (!f.exists())
					f.mkdirs();
				continue;
			}
			bis = new BufferedInputStream(zf.getInputStream(ze));
			fos = new FileOutputStream(new File(fileSavePath + File.separator
					+ ze.getName()));
			int len = 0;
			while ((len = bis.read(b)) != -1) {
				fos.write(b, 0, len);
			}
			fos.flush();
			fos.close();
			bis.close();
		}
		zf.close();
	}

}

你可能感兴趣的:(java,apache,压缩,ArrayList)