Files
assistant-android/app/src/main/java/com/gh/common/util/GzipUtils.java

115 lines
3.1 KiB
Java

package com.gh.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
private final static int BUFFER = 1024;
public static byte[] compressBytes(byte[] compressed) {
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = null;
try {
bais = new ByteArrayInputStream(compressed);
baos = new ByteArrayOutputStream();
compress(bais, baos);
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return compressed;
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 数据压缩
*/
public static void compress(InputStream is, OutputStream os) throws IOException {
GZIPOutputStream gos = null;
try {
gos = new GZIPOutputStream(os);
int count;
byte data[] = new byte[BUFFER];
while ((count = is.read(data, 0, BUFFER)) != -1) {
gos.write(data, 0, count);
}
gos.flush();
gos.finish();
gos.close();
} finally {
if (gos != null) {
gos.close();
}
}
}
public static byte[] decompressBytes(byte[] compressed) {
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = null;
try {
bais = new ByteArrayInputStream(compressed);
baos = new ByteArrayOutputStream();
decompress(bais, baos);
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return compressed;
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 数据解压缩
*/
public static void decompress(InputStream is, OutputStream os) throws IOException {
GZIPInputStream gis = null;
try {
gis = new GZIPInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}
} finally {
if (gis != null) {
gis.close();
}
}
}
}