1

The same method (writeInt()) in ObjectOutputStream and DataOutputStream writes different data? Isn't it supposed to be equal for primitive types?

        // Output: 14 bytes file
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file_14bytes.bin"));
        out.writeInt(1);
        out.writeInt(2);
        out.close();

        // Output: 8 bytes file
        DataOutputStream dout= new DataOutputStream(new FileOutputStream("file_8bytes.bin"));
        dout.writeInt(3);
        dout.writeInt(4);
        dout.close();

For example, I wanted to send objects info on first connection using objectoutputstream's writeObject() method, and then send x, y floats in loop with OOS's writeInt().

  • `ObjectOutputStream` is when you want to use Java serialization (which is somewhat discouraged due to several reasons, including security considerations). `DataOutputStream` is when you want to have total control over how you write each byte. Judging from your question you want to use the later. – Joachim Sauer Jun 04 '18 at 07:55

1 Answers1

2

ObjectOutputStream is designed to write objects and writes some meta data when writing any information including primitives.

Also OOS is buffered so you might not see all the bytes written immediately in the underlying stream.

Note: a writeInt uses 4 bytes with DataOutputStream.

send x, y floats in loop with OOS's writeInt()

I suggest you use writeFloat(f) to write floats.

If you have an array of floats I suggest you use writeObject() e.g.

oos.writeObject(someShape);
oos.writeObject(floatArray);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130