压缩和解压缩java中的字符串数据 [英] compression and decompression of string data in java
问题描述
我使用以下代码来压缩和解压缩字符串数据,但我遇到的问题是,它很容易被压缩而没有错误,但是解压缩方法会引发跟随错误。
I am using the following code to compress and decompress string data, but the problem which I am facing is, it is easily getting compressed without error, but decompress method throws following error.
线程main中的异常java.io.IOException:不是GZIP格式
Exception in thread "main" java.io.IOException: Not in GZIP format
public static void main(String[] args) throws Exception {
String string = "I am what I am hhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
+ "bjggujhhhhhhhhh"
+ "rggggggggggggggggggggggggg"
+ "esfffffffffffffffffffffffffffffff"
+ "esffffffffffffffffffffffffffffffff"
+ "esfekfgy enter code here`etd`enter code here wdd"
+ "heljwidgutwdbwdq8d"
+ "skdfgysrdsdnjsvfyekbdsgcu"
+"jbujsbjvugsduddbdj";
System.out.println("after compress:");
String compressed = compress(string);
System.out.println(compressed);
System.out.println("after decompress:");
String decomp = decompress(compressed);
System.out.println(decomp);
}
public static String compress(String str) throws Exception {
if (str == null || str.length() == 0) {
return str;
}
System.out.println("String length : " + str.length());
ByteArrayOutputStream obj=new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
String outStr = obj.toString("UTF-8");
System.out.println("Output String length : " + outStr.length());
return outStr;
}
public static String decompress(String str) throws Exception {
if (str == null || str.length() == 0) {
return str;
}
System.out.println("Input String length : " + str.length());
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("UTF-8")));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
System.out.println("Output String lenght : " + outStr.length());
return outStr;
}
仍然无法弄清楚如何解决这个问题!!!
Still couldn't figure out how to fix this issue!!!
推荐答案
这是因为
String outStr = obj.toString("UTF-8");
发送 byte []
你可以从 ByteArrayOutputStream
获取和在 ByteArrayInputStream的
来构建你的 GZIPInputStream 使用它作为这样的code>。以下是您的代码中需要进行的更改。
Send the byte[]
which you can get from your ByteArrayOutputStream
and use it as such in your ByteArrayInputStream
to construct your GZIPInputStream
. Following are the changes which need to be done in your code.
byte[] compressed = compress(string); //In the main method
public static byte[] compress(String str) throws Exception {
...
...
return obj.toByteArray();
}
public static String decompress(byte[] bytes) throws Exception {
...
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
...
}
这篇关于压缩和解压缩java中的字符串数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!