Object serialization and random access in java

2.5k Views Asked by At

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

2

There are 2 best solutions below

1
On

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
0
On

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.