java - Protocol Buffer : reading all serialized messages from file

标签 java protocol-buffers

我正在尝试序列化和反序列化 protobuf 消息。按照 documentation 中的示例,我写:

ByteArrayOutputStream out = new ByteArrayOutputStream(...);
ArrayList<AddressBookProtos.Person> messages = ...;
for (int i = 0; i < messages.size; i++){
  messages.writeTo(out);
  out.flush();
}
out.close();

当读回消息时,我希望写:

ByteArrayInputStream in = new ByteArrayInputStream(...);
ArrayList<AddressBookProtos.Person> messages = new ArrayList<...>();
while (in.available() > 0) {
   messages.add(AddressBookProtos.Person.parseFrom(in));
}

但是,我总是只返回一个结果。其他结果去哪儿了?

最佳答案

你必须使用 writeDelimitedTo/parseDelimitedFrom 或实现您自己的基于定界符的解决方案。

根据 javadoc:

... writes the size of the message as a varint before writing the data. This allows more data to be written to the stream after the message without the need to delimit the message data yourself. Use MessageLite.Builder.mergeDelimitedFrom(InputStream) (or the static method YourMessageType.parseDelimitedFrom(InputStream)) to parse messages written by this method.

关于java - Protocol Buffer : reading all serialized messages from file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39252479/

相关文章:

java - 无法使用 JavaCompiler 编译 @Entity 等注释

java - %trimmedwindow.label.eclipseSDK 作为标题栏文本 : Bug 373988

macos - 完全卸载protobuf

java - gRPC——在 Protobuf 中将 .png 图像从 Java 客户端发送到 Python 服务器

java - 为什么 count++ 在我的代码中不起作用?

java - 通过触摸屏幕移动矩形

java - 在派生类中省略 throws 声明

java - protoc-gen-java代码使用Inline对象提示语法错误

json - 如何在 Go 运行时创建 "duck-typed"grpc protobuf 消息?

protocol-buffers - 如何编写自己的 protobuf 代码生成器