Java 中整数和字节缓冲区到输出流的序列化
Serialization of integer and bytebuffer to outputstream in Java
我有一个序列化代码可以将对象序列化到字节缓冲区。我想先将缓冲区的长度写入流,然后是字节缓冲区本身。这是我写入输出流的方式:
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();
我验证了这段代码,它似乎工作正常。但是当我尝试反序列化时,我无法正确地做到这一点。这是我的反序列化程序代码片段:
DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
int objSize = in.readInt();
byte[] byteArray = new byte[objSize];
...
问题是没有从流中正确读取长度。
谁能帮我弄清楚我在这里遗漏了什么?
write
写入一个字节。 readInt
读取 4 个字节并将它们组合成一个 int
.
您可能想用 writeInt
写入长度(将 int
分成 4 个字节并写入)。
我有一个序列化代码可以将对象序列化到字节缓冲区。我想先将缓冲区的长度写入流,然后是字节缓冲区本身。这是我写入输出流的方式:
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();
我验证了这段代码,它似乎工作正常。但是当我尝试反序列化时,我无法正确地做到这一点。这是我的反序列化程序代码片段:
DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
int objSize = in.readInt();
byte[] byteArray = new byte[objSize];
...
问题是没有从流中正确读取长度。
谁能帮我弄清楚我在这里遗漏了什么?
write
写入一个字节。 readInt
读取 4 个字节并将它们组合成一个 int
.
您可能想用 writeInt
写入长度(将 int
分成 4 个字节并写入)。