网络上传输数据大部分都需要压缩数据后传递,常见的有zip方式压缩/解压缩
class="java" name="code">
/**
* 数据压缩
* @param data
* @return
*/
public static byte[] dataGZip(byte[] data)
{
ByteArrayInputStream bais = null;
GZIPOutputStream gos = null;
ByteArrayOutputStream baos = null;
try
{
bais = new ByteArrayInputStream(data);
baos = new ByteArrayOutputStream();
gos = new GZIPOutputStream(baos);
byte[] buf = new byte[1024*1024];
int num;
while ((num = bais.read(buf)) != -1) {
gos.write(buf, 0, num);
}
gos.finish();
gos.flush();
byte[] output = baos.toByteArray();
return output;
} catch (IOException e)
{
log.error(e.getMessage(), e);
} finally
{
if (null != gos)
{
try
{
gos.close();
} catch (IOException e)
{
}
}
if (null != baos)
{
try
{
baos.close();
} catch (IOException e)
{
}
}
if (null != bais)
{
try
{
bais.close();
} catch (IOException e)
{
}
}
}
return null;
}
/**
* 数据解压缩
* @param data
* @return
*/
public static byte[] dataUnGZip(byte[] data)
{
ByteArrayInputStream bais = null;
GZIPInputStream gis = null;
ByteArrayOutputStream baos = null;
try
{
bais = new ByteArrayInputStream(data);
gis = new GZIPInputStream(bais);
baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024*1024];
int num;
while((num=gis.read(buf))!=-1)
{
baos.write(buf, 0, num);
}
byte[] ret = baos.toByteArray();
return ret;
} catch (IOException e)
{
log.error(e.getMessage(), e);
} finally
{
if (null != baos)
{
try
{
baos.close();
} catch (IOException e)
{
}
}
if (null != gis)
{
try
{
gis.close();
} catch (IOException e)
{
}
}
if (null != bais)
{
try
{
bais.close();
} catch (Exception e)
{
}
}
}
return null;
}