0

I'm trying to use ObjectOutputStream over a DeflaterOutputStream to write deflated data into an underlying stream. But when I try to read the data with their InputStream counterparts, an exception is thrown. It is worth of note that replacing Deflate{Output,Input}Stream with GZip{Output,Input}Stream, it works as expected. An example code that shows this behavior can be seen below:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) {
    oos.writeObject("test");
}

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try(ObjectInputStream oos = new ObjectInputStream(new DeflaterInputStream(bais))) {
    System.out.println(oos.readObject());
}

It throws the following exception:

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 789CAB98
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
    at Main.main(Main.java:23)

Does anyone know why exacly this happens?

Juan Lopes
  • 10,143
  • 2
  • 25
  • 44

1 Answers1

1

I've already figured it out and it is a silly mistake. But answering my own question so future people don't fall for it again:

The inverse class of DeflaterOutputStream is InflaterInputStream, not DeflaterInputStream. So the code should look like the one below:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) {
    oos.writeObject("test");
}

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try(ObjectInputStream oos = new ObjectInputStream(new InflaterInputStream(bais))) {
    System.out.println(oos.readObject());
}
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44