java 实现对字符串的压缩跟解压
java 实现对字符串的压缩和解压
压缩字符串:
1. 创建字符串写入输出流os, 用于接收压缩后的byte[]
2. 用os 创建 GZIPOutputStream 对象gos
3. 将要压缩的字符串写入gos
4. 关闭gos
5. 从os中获取压缩后的内容
注意: 第4步和第5步顺序不能颠倒, 否则会抛出异常java.io.EOFException: Unexpected end of ZLIB input stream.
完整代码如下:
public static byte[] zip(String src) {
ByteArrayOutputStream os = null;
GZIPOutputStream gos = null;
byte[] dest = null;
try {
if (src == null) {
return dest;
}
os = new ByteArrayOutputStream();
gos = new GZIPOutputStream(os);
gos.write(src.getBytes("utf-8"));
IOUtils.closeQuietly(gos);
dest = os.toByteArray();
}catch (Exception e) {
throw new RuntimeException("Error zip string:" + src, e);
}finally {
IOUtils.closeQuietly(os);
}
return dest;
}
解压字符串:
大致过程和压缩差不多,就不啰嗦了.
注意要先关闭GZIPInputStream 再获取内容
public static String unzip(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayInputStream is = null;
ByteArrayOutputStream os = null;
GZIPInputStream gis = null;
String dest = null;
try {
is = new ByteArrayInputStream(bytes);
os = new ByteArrayOutputStream();
gis = new GZIPInputStream(is);
byte[] buffer = new byte[100];
for (int length = gis.read(buffer, 0, buffer.length); length > 0; length = gis.read(buffer)) {
os.write(buffer, 0, length);
}
IOUtils.closeQuietly(gis);
IOUtils.closeQuietly(is);
dest = os.toString("utf-8");
}catch (Exception e) {
throw new RuntimeException("Error unzip bytes:" + bytes, e);
}finally {
IOUtils.closeQuietly(os);
}
return dest;
}
压缩字符串:
1. 创建字符串写入输出流os, 用于接收压缩后的byte[]
2. 用os 创建 GZIPOutputStream 对象gos
3. 将要压缩的字符串写入gos
4. 关闭gos
5. 从os中获取压缩后的内容
注意: 第4步和第5步顺序不能颠倒, 否则会抛出异常java.io.EOFException: Unexpected end of ZLIB input stream.
完整代码如下:
public static byte[] zip(String src) {
ByteArrayOutputStream os = null;
GZIPOutputStream gos = null;
byte[] dest = null;
try {
if (src == null) {
return dest;
}
os = new ByteArrayOutputStream();
gos = new GZIPOutputStream(os);
gos.write(src.getBytes("utf-8"));
IOUtils.closeQuietly(gos);
dest = os.toByteArray();
}catch (Exception e) {
throw new RuntimeException("Error zip string:" + src, e);
}finally {
IOUtils.closeQuietly(os);
}
return dest;
}
解压字符串:
大致过程和压缩差不多,就不啰嗦了.
注意要先关闭GZIPInputStream 再获取内容
public static String unzip(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayInputStream is = null;
ByteArrayOutputStream os = null;
GZIPInputStream gis = null;
String dest = null;
try {
is = new ByteArrayInputStream(bytes);
os = new ByteArrayOutputStream();
gis = new GZIPInputStream(is);
byte[] buffer = new byte[100];
for (int length = gis.read(buffer, 0, buffer.length); length > 0; length = gis.read(buffer)) {
os.write(buffer, 0, length);
}
IOUtils.closeQuietly(gis);
IOUtils.closeQuietly(is);
dest = os.toString("utf-8");
}catch (Exception e) {
throw new RuntimeException("Error unzip bytes:" + bytes, e);
}finally {
IOUtils.closeQuietly(os);
}
return dest;
}