Reputation: 1392
I have a serialization code that can serialize an object to a bytebuffer. I want to write the length of the buffer first to the stream followed by the bytebuffer itself. Here is how I am writing to the outputStream:
MyObject = new MyObject();
//fill in MyObject
...
DataOutputStream out = new DataOutputStream(new FileOutputStream("a.txt"));
ByteBuffer buffer = MySerializer.encode(myObject);
int length = buffer.remaining();
out.write(length);
WritableByteChannel channel = Channels.newChannel(out);
channel.write(buffer);
out.close();
I verified this code and it seems to be working fine. But when I try to deserialize, I am not able to do it correctly. Here is the snippet of my deserializer code :
DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
int objSize = in.readInt();
byte[] byteArray = new byte[objSize];
...
The problem is that the length is not being read properly from stream.
Can anyone help me figure out what am I missing here?
Upvotes: 0
Views: 357
Reputation: 58888
write
writes a byte. readInt
reads 4 bytes and combines them to make an int
.
You probably want to write the length with writeInt
(which splits the int
into 4 bytes and writes those).
Upvotes: 2