java 字符串压缩算法,如何压缩Java中的字符串?

博客讨论了使用GZIPOutputStream压缩短字符串(长度小于20)时,压缩结果可能比原始字符串更长的问题。这通常是因为压缩算法对于较短的数据存在空间开销,只有在数据足够大时才能体现出压缩效果。文章建议,对于包含重复模式的字符串,可以尝试使用Huffman编码或运行长度编码来压缩,但对于非常短的字符串,压缩可能并不容易或不总是有效。
摘要由CSDN通过智能技术生成

I use GZIPOutputStream or ZIPOutputStream to compress a String (my string.length() is less than 20), but the compressed result is longer than the original string.

On some site, I found some friends said that this is because my original string is too short, GZIPOutputStream can be used to compress longer strings.

so, can somebody give me a help to compress a String?

My function is like:

String compress(String original) throws Exception {

}

Update:

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.zip.GZIPOutputStream;

import java.util.zip.*;

//ZipUtil

public class ZipUtil {

public static String compress(String str) {

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 void main(String[] args) throws IOException {

String string = "admin";

System.out.println("after compress:");

System.out.println(ZipUtil.compress(string));

}

}

The result is :

NUYbH.jpg

解决方案

Compression algorithms almost always have some form of space overhead, which means that they are only effective when compressing data which is sufficiently large that the overhead is smaller than the amount of saved space.

Compressing a string which is only 20 characters long is not too easy, and it is not always possible. If you have repetition, Huffman Coding or simple run-length encoding might be able to compress, but probably not by very much.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值