副标题#e#
数据字段一般都是生存原文的,一来利便在数据库修改和维护,而来有一些查询要用到它。可是在有些时候,我们无需生存原文了,好比在论坛,博客等数据里的内容字段,一般利用Clob范例,其很少参加搜索,并且就算要全文检索,我们也不推荐利用数据库的like 等,而应该用第三方的全文检索东西,好比lucene等实现。
这类数据都是大量的文本数据,有很大的可压缩性。由于一些原因,我的数据库已经高出我能容忍的巨细了,所以想到了是否可以把这个数据压缩存储来节减空间,于是有了如下的实验。
压缩算法就先不外多思量了,就用Zip举办实验就可以了。先看看如何把字符串压缩息争压缩的算法。
package com.laozizhu.article.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* 把字符串利用ZIP压缩息争压缩的代码。
*
* @author JAVA世纪网(java2000.net, laozizhu.com)
*/
public class StringZip {
public static String zipString(String str) {
try {
ByteArrayOutputStream bos = null;
GZIPOutputStream os = null;
byte[] bs = null;
try {
bos = new ByteArrayOutputStream();
os = new GZIPOutputStream(bos);
os.write(str.getBytes());
os.close();
bos.close();
bs = bos.toByteArray();
return new String(bs, "iso-8859-1");
} finally {
bs = null;
bos = null;
os = null;
}
} catch (Exception ex) {
return str;
}
}
public static String unzipString(String str) {
ByteArrayInputStream bis = null;
ByteArrayOutputStream bos = null;
GZIPInputStream is = null;
byte[] buf = null;
try {
bis = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
bos = new ByteArrayOutputStream();
is = new GZIPInputStream(bis);
buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
bos.write(buf, 0, len);
}
is.close();
bis.close();
bos.close();
return new String(bos.toByteArray());
} catch (Exception ex) {
return str;
} finally {
bis = null;
bos = null;
is = null;
buf = null;
}
}
}
#p#副标题#e#
然后就是如何压缩息争压缩,应该放在那边的问题。我思量了一下,发明JavaBean这对象真的有趣,竟然可以实现透明压缩息争压缩。看代码:
private String content;
// 增加一个是否压缩的字段,没步伐,有些字段压缩了反到更长了
private boolean ziped;
public boolean isZiped() {
return ziped;
}
public void setZiped(boolean ziped) {
this.ziped = ziped;
}
**
* 读取内容。
* @return the content
*/
public String getContent() {
// 解码
if (isZiped()) {
return StringZip.unzipString(content);
}
return content;
}
/**
* 配置新的内容
* @param content the content to set
*/
public void setContent(String content) {
if (content == null || content.length() < 512) {
this.content = content;
ziped = false;
} else {
// 实验编码
this.content = StringZip.zipString(content);
// 假如编码后的数据更长
if (this.content.length() > content.length()) {
this.content = content;
ziped = false;
} else {
ziped = true;
}
}
}
增加了一个是否压缩的属性。
在读取时,按照是否压缩的符号举办操纵,在配置时,按照数据长度和压缩的结果更新数据,并配置压缩符号。
通过这个,数据将被压缩生存,一般的文本压缩率照旧很高的,到底有多高,你本身测试看看就知道了。