0

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) {
        this.val=val;
        this.index=index;
    }
}
Community
  • 1
  • 1
Daar
  • 3,385
  • 4
  • 20
  • 18

1 Answers1

7

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.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • 1
    Alternatively, why not just serialize the entire list? That's what serialization is for - so you don't have to write code to iterate or recurse over objects! – Robin Green Apr 18 '11 at 20:54
  • And specifically, as it says in the Javadoc, available() == 0 is not a valid test for EOF. – user207421 Apr 19 '11 at 01:13