Java GZIP压缩的使用
程序员文章站
2024-03-13 23:30:46
...
为了减小服务器负担,传递字符串内容通常要进行压缩,同时也能增强传输的速度,在java中GZIP压缩基本实现代码如下:
/**
* 将压缩字符串解压为字符串
* @param file 压缩文件
* @return 解压为字符串
* @throws Exception
*/
public static String deCompressString(File file) throws Exception{
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream byteOut2 = new ByteArrayOutputStream();
decompress(fis, byteOut2);
byte[] bs = byteOut2.toByteArray();
return new String(bs,"utf-8");
}
/**
* 将字符串压缩到一个file中
* @param str 字符串
* @param file 压缩到的file
* @throws Exception
*/
public static void compressString(String str,File file) throws Exception{
FileOutputStream fos = new FileOutputStream(file);
ByteArrayInputStream byteIn = new ByteArrayInputStream(str.getBytes("utf-8"));
compress(byteIn, fos);
}
/**
* GZIP数据压缩
* @param is
* @param os
* @throws Exception
*/
public static void compress(InputStream is, OutputStream os) throws Exception {
GZIPOutputStream 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.finish();
gos.flush();
gos.close();
}
/**
* GZIP数据解压缩
* @param is
* @param os
* @throws Exception
*/
public static void decompress(InputStream is, OutputStream os) throws Exception {
GZIPInputStream gis = new GZIPInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}
gis.close();
}
上一篇: Linux中压缩和解压缩指令
下一篇: 不同坐标体系的转换