4

I need to save a string on a file and I am using DeflaterOutputStream to compress. when I try to decompress I can't get the original String. I get an uncleared symbols. Her is my code:

    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();

}

I don't where exactly is the problem . I though it's in converting the byte array to String but I tried it and it is working. You can check this website http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/

1 Answers1

6

You have a simple but hard to notice bug. You are not actually using your InflaterInputStream to read the data. You are just opening and closing it. Your code reading the file is:

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

Should be

 while ((b = ini.read()) != -1) {
lreeder
  • 12,047
  • 2
  • 56
  • 65