如何压缩Java中的字符串? [英] How to compress a String in Java?
问题描述
我使用 GZIPOutputStream
或 ZIPOutputStream
压缩一个String(my string.length )
小于20),但是压缩的结果比原始字符串长。
在某些网站上,我发现一些朋友说这是因为我的原始字符串太短, GZIPOutputStream
可以用于压缩更长的字符串。
有人给我帮助压缩一个String?
我的函数是:
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));
}
}
结果是:
压缩算法几乎总是具有某种形式的空间开销,这意味着它们仅在压缩足够大的数据时有效,以致开销小于所保存的空间量。 p>
压缩一个只有20个字符长的字符串不是太容易,而且并不总是可能的。如果你有重复,Huffman编码或简单的游程长度编码可能能够压缩,但可能不是非常。
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 :
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.
这篇关于如何压缩Java中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!