Harvey Adcock Harvey Adcock - 4 months ago 21
Java Question

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

I'm trying to get an

ObjectInputStream
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
mark
and
reset
) for some other code to deal with. I've tried wrapping the
InputStream
retrieved from the
Socket
(
s
in the following example) in a
BufferedInputStream
before wrapping it in an
ObjectInputStream
as I believed to be the solution, however when calling
ois.markSupported()
false is still returned. Below is that attempt:

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


Any help greatly appreciated!

Answer

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().