工具方法:

	/**
	 * 新建文件(.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");
	}

 

结果:

java用IO流创建zip压缩文件

java用IO流创建zip压缩文件

 

java用IO流创建zip压缩文件

相关文章: