GZIP字符串压缩无法解压缩'£'字符

时间:2012-02-15 07:51:04

标签: java character-encoding compression gzip

我有以下代码用于压缩字符串(为清晰起见,删除了错误和资源处理):

import java.util.zip.GZIP*;
import java.io.*;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import com.Ostermiller.util.Base64;

//Code to compress the string
ByteArrayOutputStream output = new ByteArrayOutputStream(65536);
BufferedWriter writer = new BufferedWriter(
           new OutputStreamWriter(new GZIPOutputStream(output)));
writer.write(stringContents);
String compressedString =  new String(Base64.encode(output.toByteArray()));

...

//Code to decompress the string
byte[] compressedData = Base64.decode(compressedString.getBytes());
BufferedInputStream reader = new BufferedInputStream(
           new GZIPInputStream(new ByteArrayInputStream(compressedData)));
String uncompressedString = IOUtils.toString(reader, "UTF-8");

我们在尝试编码然后解码其中带有'£'的字符串时遇到错误。具体来说,字符串压缩OK,但在尝试解压缩字符串时,我们得到以下堆栈跟踪:

sun.io.MalformedInputException
at sun.io.ByteToCharUTF8.convert(ByteToCharUTF8.java(Compiled Code))
at sun.nio.cs.StreamDecoder$ConverterSD.convertInto(StreamDecoder.java:287)
at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:337)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:223)
at java.io.InputStreamReader.read(InputStreamReader.java:208)
at java.io.Reader.read(Reader.java:113)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1128)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1104)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1078)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:382)

有谁能告诉我我的方式错误以及如何解决这种情况?有没有更好的方法来做到这一点?非常感谢提前。

1 个答案:

答案 0 :(得分:5)

压缩数据时应指定字符编码:

BufferedWriter writer = new BufferedWriter(
           new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8"));

如果不这样做,则根据系统默认字符编码将文本转换为字节,在您的情况下,该编码不是UTF-8。