Java Zip压缩并生成

代码留存,zip压缩。

public static void zip(File file, File zipFile) throws Exception {
		ZipOutputStream output = null;
		try {
			output = new ZipOutputStream(new FileOutputStream(zipFile));
//如出现编码混乱请加入编码要求,一般出现在英文系统中
                        output.setEncoding("UTF-8");
			createdir = false;
			zipFile(output, file, "");
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (output != null) {
				output.flush();
				output.close();
			}
		}
	}

	public static void zipFile(ZipOutputStream output, File file,
			String basePath) throws IOException {
		FileInputStream input = null;
		try {
			if (file.isDirectory()) {
				File list[] = file.listFiles();
				basePath = basePath + (basePath.length() == 0 ? "" : "/")
						+ file.getName();
				if (!createdir) {
					basePath = "";
					createdir = true;
				}
				for (File f : list)
					zipFile(output, f, basePath);
			} else {
				basePath = (basePath.length() == 0 ? "" : basePath + "/")
						+ file.getName();
				output.putNextEntry(new ZipEntry(basePath));
				input = new FileInputStream(file);
				int readLen = 0;
				byte[] buffer = new byte[1024 * 8];
				while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1)
					output.write(buffer, 0, readLen);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (input != null)
				input.close();
		}
	}

 

转载于:https://my.oschina.net/discussjava/blog/1595904

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值