Reputation: 13
I can make my program write a .dat
file with an array of Node
(an object that contains registry information:name,telephone numbers,...) using ObjectOutputStream
, but I am having problems reading this same file, since the file contains an object that is different from the Node[]
I used earlier.
My problems will be solved if I can make one of them:
Object
into an object type Node[]
, orreadNode[]();
I don't known the official name for this, so I am having problems finding an answer.
Upvotes: 1
Views: 253
Reputation: 262474
The Object returned from the ObjectInputStream will have the same type it had when you wrote it to the file in the first place.
You will have to cast it at runtime, though, because the compiler cannot know what type that will be.
Object obj = stream.readObject();
Node[] nodes = (Node[]) obj;
If your format is flexible, so that you do not know what exactly to expect, you can use instanceof to check the various possibilities first.
if (obj instanceof Node[]){
// do something
}
else if (obj instanceof String) {
// do something
}
else {
throw new IOException("unexpected object in data stream "+ obj);
}
Upvotes: 3