Rectangle 27 0

android Reading Java serialized object that has been split across two files?


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.SequenceInputStream;

...

ObjectInputStream in = null;

try {
    in = new ObjectInputStream(
        new SequenceInputStream(
                new FileInputStream("myobj.part1"),
                new FileInputStream("myobj.part2")));

    Foo foo = (Foo) in.readObject();

    // Do something with the deserialized object...
    foo.doSomething();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        try { 
            in.close();
        } catch (IOException e) { }
    }
}

As Tom Hawtin pointed out in the comments, you should be able to use Java's built-in SequenceInputStream class to deserialize an object that is split across multiple files. This approach also allows you to deserialize an object split across any number of files, because SequenceInputStream's constructor accepts two InputStream objects, one of which could be another SequenceInputStream.

I created a small example that should work on Android, although I have only tested it on a desktop Java installation. The example works on the assumption that you have serialized an object of type Foo and split the serialized version between two files names myobj.part1 and myobj.part2.

The example is pretty self explanatory, but if you have any questions, please let me know.

Note