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

…衆ロ難τιáo~ 提交于 2019-12-13 21:35:24

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/38814424/how-can-i-get-an-objectinputstream-that-supports-mark-reset

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