What is the best way to fully read a stream of objects from a file in Java?

后端 未结 4 1358
星月不相逢
星月不相逢 2021-01-14 17:33

I\'m creating a potentially long log of objects and do not want to keep them all in memory before writing to a file, so I can\'t write a serialized collection of the objects

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 17:58

    Write a boolean after each object, with the "last" object being followed by a false. So, in your stream that you write out:

    true
    
    true
    
    true
    
    false
    
    
    

    Then, when reading them back in, you check the flag (you know there will always be one after each object) to decide whether or not to read another one.

    boolean will be stored very compactly in a serialization stream, so it shouldn't add much to the file size.

    提交回复
    热议问题