gzip: Inflate float array in java

I am trying to figure out a way to inflate/deflate an array of floats in java.

My code to deflate looks like this, which seems to work fine.

List<Float> floats = ...;

ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
objectOut.writeObject(floats.toArray(new Float[0]));

return baos.toByteArray();

I am having issues with inflating the byte array again back to a float[] array.

Below is one of my attempts, which fails (it even generates NaN floats)

byte[] bytes =....
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream gzipIn = new GZIPInputStream(bais);
ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
List<Float> floats = new ArrayList<>()

byte[] buffer = new byte[4]

while (gzipIn.read(buffer) >= 0) {
    Float f  = ByteBuffer.wrap(buffer).float
    floats.add(f)
}
return floats

I am be able to use any other classes - I just am not able to block as this would be running inside a non blocking event driven server.

Jon Skeet
people
quotationmark

You're using different calls - you're calling writeObject in the writing part, then assuming that you can just read 4 bytes at a time in the reading part.

Why not just use:

Float[] floats = (Float[]) objectIn.readObject();

? That would match your writing code. You can then wrap the array in a list if you want to.

people

See more on this question at Stackoverflow