Object serialization and random access in java

限于喜欢 提交于 2019-12-11 20:10:37

问题


Can you use Java's built in object serialization with a random access file? My motivation is my answer to this question.


回答1:


You could use serialization with a random access file, but you'll have to build the infrastructure yourself. There is no way to get the size of serialization without actually serializing.

I assume you want to store multiple serialized objects in the same file, so you'll need to do something like:

  1. Store the serialized objects, keeping track of the offsets within the stream until the end, and then write a table of contents at the end of the file. This is similar to the zip file format.

-or-

  1. Write "placeholder" bytes for the size, then serialize the object to the stream, then seek back to the placeholder and write the number of bytes actually written.



回答2:


You could (using java's ByteArrayOutputStream and ByteArrayInputStream), but it would be a very bad idea. Java's built in object serialization isn't memoryless. "The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written." You could get around this by creating a new instance of ObjectOutputStream/ObjectInputStream for each object you write/read, but that would make your file excessively large.

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

        objectOutputStream.writeObject(1);
        System.out.println(byteArrayOutputStream.size());
        byteArrayOutputStream.reset();

        objectOutputStream.writeObject(2);
        System.out.println(byteArrayOutputStream.size());
        byteArrayOutputStream.reset();

        objectOutputStream.writeObject(2);
        System.out.println(byteArrayOutputStream.size());
        byteArrayOutputStream.reset();

        objectOutputStream.writeObject(3);
        System.out.println(byteArrayOutputStream.size());
        byteArrayOutputStream.reset();

        objectOutputStream.close();
    }
}

Output

  • 81
  • 10
  • 5
  • 10


来源:https://stackoverflow.com/questions/27435943/object-serialization-and-random-access-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!