首页>代码>java压缩和解压指定文件夹下的文件实例>/com.zip/src/main/java/com/chen/util/CompressionZip.java
package com.chen.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩文件成zip
 * 
 * @author chenguoji
 *
 */
public class CompressionZip {

	private static int k = 1; // 定义递归次数变量

	public CompressionZip() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 压缩文件
	 * 
	 * @param zipFileName
	 *            保存目录
	 * @param inputFile
	 *            压缩的文件目录
	 * @throws Exception
	 */
	public static void zip(String zipFileName, File inputFile) {
		try {

			System.out.println("压缩中...");
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					zipFileName));
			BufferedOutputStream bo = new BufferedOutputStream(out);
			zip(out, inputFile, inputFile.getName(), bo);
			bo.close();
			out.close(); // 输出流关闭
			System.out.println("压缩完成");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 文件下所有目录
	 * 
	 * @param out
	 * @param f
	 * @param base
	 * @param bo
	 * @throws Exception
	 */
	public static void zip(ZipOutputStream out, File f, String base,
			BufferedOutputStream bo) throws Exception { // 方法重载
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			if (fl.length == 0) {
				out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
				System.out.println(base + "/");
			}
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
			}
			System.out.println("第" + k + "次递归");
			k++;
		} else {
			out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
			System.out.println(base);
			FileInputStream in = new FileInputStream(f);
			BufferedInputStream bi = new BufferedInputStream(in);
			int b;
			while ((b = bi.read()) != -1) {
				bo.write(b); // 将字节流写入当前zip目录
			}
			bi.close();
			in.close(); // 输入流关闭
		}
	}

	/**
	 * 压缩单个文件
	 * 
	 * @param srcfile  压缩文件
	 * @param basedir  输出的压缩文件存在目录
	 */
	public static void zipFile(File srcfile,String basedir) {
		//判断是否是单个文件
		if(!srcfile.isFile()) 
			return;
		if (!srcfile.exists())
			return;
		System.out.println("开始压缩单个文件");
		File targetFile = new File(basedir);
		
		byte[] buf = new byte[1024];
		FileInputStream in = null;
		ZipOutputStream out = null;  
		try {
			out = new ZipOutputStream(new FileOutputStream(targetFile)); 
			int len;
			in = new FileInputStream(srcfile);
			out.putNextEntry(new ZipEntry(srcfile.getName()));

			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			System.out.println("压缩单个文件成功");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.closeEntry();
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 压缩文件或路径
	 * 
	 * @param zip
	 *            压缩的目的地址
	 * @param srcFiles
	 *            压缩的源文件
	 */
	public static void zipFile(String zip, List<File> srcFiles) {
		try {
			if (zip.endsWith(".zip") || zip.endsWith(".ZIP")) {
				ZipOutputStream _zipOut = new ZipOutputStream(
						new FileOutputStream(new File(zip)));
				for (File _f : srcFiles) {
					//选择指定压缩文件
					if(_f.getName().equals("a1.jpg") || _f.getName().equals("b1.jpg"))
						handlerFile(zip, _zipOut, _f, "");
				}
				_zipOut.close();
			} else {
				System.out.println("target file[" + zip+ "] is not .zip type file");
			}
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}

	/**
	 * 
	 * @param zip
	 *            压缩的目的地址
	 * @param zipOut
	 * @param srcFile
	 *            被压缩的文件信息
	 * @param path
	 *            在zip中的相对路径
	 * @throws IOException
	 */
	private static void handlerFile(String zip, ZipOutputStream zipOut,
			File srcFile, String path) throws IOException {
		System.out.println(" begin to compression file[" + srcFile.getName()
				+ "]");
		if (!"".equals(path) && !path.endsWith(File.separator)) {
			path += File.separator;
		}
		if (!srcFile.getPath().equals(zip)) {
			if (srcFile.isDirectory()) {
				File[] _files = srcFile.listFiles();
				if (_files.length == 0) {
					zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()
							+ File.separator));
					zipOut.closeEntry();
				} else {
					for (File _f : _files) {
						handlerFile(zip, zipOut, _f, path + srcFile.getName());
					}
				}
			} else {
				InputStream _in = new FileInputStream(srcFile);
				zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()));
				int len = 0;
				byte[] _byte = new byte[1024];
				while ((len = _in.read(_byte)) > 0) {
					zipOut.write(_byte, 0, len);
				}
				_in.close();
				zipOut.closeEntry();
			}
		}
	}

}
最近下载更多
zzzyyy1  LV2 2月26日
cindyd  LV1 2021年11月1日
dybtom  LV10 2019年6月28日
武静123  LV1 2019年5月28日
18170035580  LV14 2018年11月3日
FunnyKing  LV19 2017年8月7日
最代码官方  LV167 2017年8月4日
最近浏览更多
zzzyyy1  LV2 2月26日
一只小扒菜啊 2023年10月30日
暂无贡献等级
EFWAGGFAWGR 2023年10月19日
暂无贡献等级
zhangjilu  LV18 2023年2月18日
沙漏哦  LV9 2022年9月14日
yymmdm  LV6 2022年8月10日
whfuai  LV14 2022年7月27日
wanglinddad  LV54 2022年4月22日
李海洋  LV12 2021年12月1日
cindyd  LV1 2021年11月1日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友