All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rt.core.util.ZipHelper Maven / Gradle / Ivy

There is a newer version: 1.1.17
Show newest version
package com.rt.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * zip gzip压缩/解压缩到String支持
 * 
 * 
 */
class ZipHelper {

	public ZipHelper() {
	}

	/**
	 * 解压缩
	 * 
	 * @param zipBytes
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] unzip(byte[] zipBytes) throws IOException {
		ByteArrayInputStream bais = new ByteArrayInputStream(zipBytes);
		ZipInputStream zis = new ZipInputStream(bais);
		zis.getNextEntry();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final int BUFSIZ = 4096;
		byte inbuf[] = new byte[BUFSIZ];
		int n;
		while ((n = zis.read(inbuf, 0, BUFSIZ)) != -1) {
			baos.write(inbuf, 0, n);
		}
		byte[] data = baos.toByteArray();
		zis.close();
		return data;
	}

	/**
	 * 压缩字符串
	 * 
	 * @param data
	 * @return zip byte[]
	 * @throws IOException
	 */
	public static byte[] zip(byte[] data) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ZipEntry ze = new ZipEntry("!zip!");
		ZipOutputStream zos = new ZipOutputStream(baos);
		zos.putNextEntry(ze);
		zos.write(data, 0, data.length);
		zos.close();
		byte[] zipBytes = baos.toByteArray();
		return zipBytes;
	}

	/**
	 * 解压缩
	 * 
	 * @param zipBytes
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] ungzip(byte[] zipBytes) throws IOException {
		ByteArrayInputStream bais = new ByteArrayInputStream(zipBytes);
		GZIPInputStream zis = new GZIPInputStream(bais);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final int BUFSIZ = 4096;
		byte inbuf[] = new byte[BUFSIZ];
		int n;
		while ((n = zis.read(inbuf, 0, BUFSIZ)) != -1) {
			baos.write(inbuf, 0, n);
		}
		byte[] data = baos.toByteArray();
		zis.close();
		return data;
	}

	/**
	 * 压缩字符串
	 * 
	 * @param data
	 * @return zip byte[]
	 * @throws IOException
	 */
	public static byte[] gzip(byte[] data) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		GZIPOutputStream zos = new GZIPOutputStream(baos);
		zos.write(data, 0, data.length);
		zos.close();
		byte[] zipBytes = baos.toByteArray();
		return zipBytes;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy