使用Java的DeflaterOutputStream和InflaterInputStream压缩和解压缩字符串

4

我需要将一个字符串保存到文件中,我使用DeflaterOutputStream进行压缩。但是当我尝试解压缩时,无法得到原始字符串。我得到了一些未清除的符号。 以下是我的代码:

    public static void decompress() throws Exception {
    InputStream in=new FileInputStream("E:/codes.txt"); 
    InflaterInputStream ini = new InflaterInputStream(in);
    ByteArrayOutputStream bout =new ByteArrayOutputStream(512);
    int b;
    while ((b = in.read()) != -1) {
          bout.write(b);
    }
    ini.close();
    bout.close();
    String s=new String(bout.toByteArray());
    System.out.print(s);
}

public static void compressData(byte[] data) throws Exception {
    OutputStream out=new FileOutputStream("E:/test.txt");
    Deflater d = new Deflater();
    DeflaterOutputStream dout = new DeflaterOutputStream(out, d);
    dout.write(data);
    dout.close();
}
public static void main(String[] args) throws Exception {
    compressData("My name is Motasem".getBytes());
    decompress();

}

我不确定问题出在哪里。我原以为是将字节数组转换成字符串时出了问题,但我尝试过这个方法,它是有效的。您可以查看这个网站:http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/


1
你写入"E:/test.txt";你从"E:/codes.txt"读取。 - McDowell
@McDowell 你是对的 :D - Motasem M. Al-wazir
1个回答

6
你有一个简单但不易注意到的错误。你实际上没有使用你的InflaterInputStream来读取数据,你只是打开和关闭了它。你读取文件的代码如下:
 while ((b = in.read()) != -1) {

应该是

 while ((b = ini.read()) != -1) {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接