Jim Vercoelen Jim Vercoelen - 6 months ago 40
Java Question

Java cast ObjectInputStream result to ArrayList

Is there a way to cast an OutputStream into an ArrayList at once?

I'am testing things out here and what I've got for example:

Writing:

// Some list
List<Edge> edges = = new ArrayList<>();
edges.add(new Edge...)
edges.add(new Edge...)
...

OutputStream outStream = socket.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(outStream);
out.writeObject(edges);


Reading

InputStream inStream = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(inStream);
Object inObject = in.readObject();
if (inObject.getClass() == ArrayList.class) {
System.err.println("IS LIST");
List<Edge> edges = (List<Edge>) in.readObject();
}


Result

IS LIST
Jun 01, 2016 6:15:05 PM client.Client main
SEVERE: null
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2608)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at client.Client.main(Client.java:86)

Answer

EOFException is an "End Of File" exception. It means you attempted to read data when there is no more data to be read (already at the end of the file).

This occurs because you're reading 2 objects, but you are sending only 1. Instead of calling in.readObject() a 2nd time, simply cast the object you've already read:

list = (List<Edge>) inObject;
Comments