Harvey Adcock Harvey Adcock - 1 year ago 79
Java Question

How can I get an ObjectInputStream that supports mark/reset?

I'm trying to get an

that will allow me to read data from it and, if it's not of the right type, put the data back onto the stream (using
) for some other code to deal with. I've tried wrapping the
retrieved from the
in the following example) in a
before wrapping it in an
as I believed to be the solution, however when calling
false is still returned. Below is that attempt:

ois = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));

Any help greatly appreciated!

Answer Source

I would build a higher-level abstraction on top of the stream. Something like this (pseudo-code, not finalized):

public class Buffer {
    private final ObjectInputStream in;

    private Object current;

    public Buffer(ObjectInputStream in) {
        this.in = in;

    public Object peek() {
        if (current == null) {
            current = in.readObject();
        return current;

    public void next() {
        current = in.readObject();

You would use peek() repeatedly to get the current object, and if it suits you, call next() to go to the next one.

Of course, you need to deal with exceptions, the end of the stream, closing it properly, etc. But you should get the idea.

Or, if you can just read everything in memory, then do it and create a Queue with the objects from the stream, then pass that Queue around and use peek() and poll().