java用IO流创建zip压缩文件

工具方法:

	/**
	 * 新建文件(.zip)
	 * @param datas Map数组,key是文件名,byte[]是数据
	 * @param output	输出流
	 * @param charset	编码
	 */
	public static void zipStringToOutputStream(Map<String, byte[]> datas,
			OutputStream output, String charset) {
		ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(output));
		Set<Entry<String, byte[]>> dataEntrys = datas.entrySet();
		for (Entry<String, byte[]> data : dataEntrys) {
			try {
				Assert.hasText(data.getKey(), "写入文件对象为NULL或空");
				Assert.notNull(data.getValue(), "写入文件【" + data.getKey() + "】的字符对象为NULL");
				InputStream bufferIn = new BufferedInputStream( new ByteArrayInputStream(data.getValue()) );
				byte[] bs = new byte[1024]; //容器1M
				Arrays.fill(bs, (byte) 0);
				zipout.putNextEntry(new ZipEntry(data.getKey()));//创建压缩文件内的文件
				int len = -1;
				while ((len = bufferIn.read(bs)) > 0) {//写入文件内容
					zipout.write(bs, 0, len);
				}
				bufferIn.close();
			} catch (Exception e) {
				System.out.println("字符串ZIP流写入压缩文件【" + data.getKey() + "】失败,忽略该文件压缩:" + e.getMessage());
			}
		}
		try {
			zipout.close();
		} catch (IOException e) {
			System.out.println("ZIP流关闭异常:" + e.getMessage());
		}
	}

 

测试:

	public static void main(String[] args) throws FileNotFoundException {
		FileOutputStream fout = new FileOutputStream("F:/aaa.zip");
		Map<String, byte[]> datas = new HashMap<String, byte[]>();
		datas.put("111.txt", "asdasdadfasdgads".getBytes());
		datas.put("222.txt", "asdasdadfasdgads".getBytes());
		datas.put("333.txt", "asdasdadfasdgads".getBytes());
		zipStringToOutputStream(datas , fout , "GBK");
	}

 

结果:

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值