Java中字符串压缩的操作
这段时间项目中碰到一个问题,就是在做页面操作的时候,要保存的数据长度大于了表定义的字段长度,我们现在的项目是基于component开发,由于component是属于德国人开发,且德国人不愿意更改他们的设计,所以最后没有办法最后只能想到了一个对字符串进行压缩然后把压缩后的字符串存进数据库中,当需要从数据库中取数据时,需要对取出的数据进行解压缩,以前没有碰到过这种情况,所以花了很久的时间才写好了一个对字符串进行压缩和解压缩的类,如果写的不恰当的地方或者有更好的办法,还希望各位不吝赐教,该类的代码如下:
- package com.eric.io;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.util.zip.GZIPInputStream;
- import java.util.zip.GZIPOutputStream;
-
- public class StringCompression {
-
- static String code="UTF-8";
- public static String compress(String str) throws IOException {
- System.out.println("压缩之前的字符串大小:"+str.length());
- if (str == null || str.length() == 0) {
- return str;
- }
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- GZIPOutputStream gzip = new GZIPOutputStream(out);
- gzip.write(str.getBytes());
- gzip.close();
- return out.toString("ISO-8859-1");
- }
-
- public static String uncompress(String str) throws IOException {
- System.out.println("压缩之后的字符串大小:"+str.length());
- if (str == null || str.length() == 0) {
- return str;
- }
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
- GZIPInputStream gunzip = new GZIPInputStream(in);
- byte[] buffer = new byte[256];
- int n;
- while ((n = gunzip.read(buffer)) >= 0) {
- out.write(buffer, 0, n);
- }
- return out.toString();
- }
-
- public static void main(String[] args) throws IOException {
-
- System.out.println(StringCompression.uncompress(StringCompression.compress(OracleCompressTest.append("i come from china"))));
- }
-
- }
-
-
-
-
-
-
-
-
-
|
评论暂时关闭