开发者

Why doesn't this object serializiation work?

I'm having problems with the following code. Serializing the object seems to work, but when I try to deserialize it, method in.available() returns 0 immediately(it doesn't goes into the while loop). Since the (de)serialization logic is copied from here, I guess it should work.

public class test {
    public static enum Direction {NONE, UP, DOWN, LEFT, RIGHT}
    /**
     * @param args
     */

    public static void main(String[] args) {
        LinkedList<Node> list = new LinkedList<Node>();
        list.add(new Node(1.0, 0));
        list.add(new Node(2.0, 0));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out;
        try {
            out = new ObjectOutputStream(baos);
            for(Node l:list)
                out.writeObject(l);

            baos.close();
            out.close();

            byte[] bytes = baos.toByteArray();

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInput in;

            in = new ObjectInputStream(bais);

            while (in.available() > 0) {
                Node l = (Node) in.readObject();
            }
            bais.close();
            in.close();

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}

 class Node implements Serializable {
    double val;
    int index;

    public Node(double val, int index) {
        t开发者_Go百科his.val=val;
        this.index=index;
    }
}


do not use InputStream.available(). it pretty much never does what you want it to do. you basically must just call readObject and catch the IOException which is thrown when there is no more data to read (probably an instance of EOFException).

alternately, you can first call ObjectOutputStream.writeInt() with the number of nodes you have and read that with ObjectInputStream.readInt() so that you know how many nodes to expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜