• Post Reply Bookmark Topic Watch Topic
  • New Topic

Deserializing objects

 
Rachel Swailes
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have scoured the net for a simple answer for how to get a field from a serialized object after it is read back from the file.

So I have gotten as far as saving the object to a file, reading the object back from the file, but now I am trying to get a field from the saved object.

Please help!

Thanks,
Rachel
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to cast the Object reference you read in to a reference of the type you are expecting. Let's say I serialized a java.util.Date instance:
 
Rachel Swailes
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I've tried that and I just get "null"

I have this class called AddressContactPerson. In it there are fields for the name and email and there are methods for writing it to the file and reading from the file. So I write it and then I read it using this code...

try{
FileInputStream fis = new FileInputStream(addressFile);
ObjectInputStream ois = new ObjectInputStream(fis);

AddressContactPerson aacp = (AddressContactPerson)ois.readObject();
System.out.println(aacp.getName());
ois.close();
fis.close();

}catch(etc...


And sometimes it doesn't print and sometimes it does and it prints null. Should I post all my code?

Thanks!
Rachel
 
Rachel Swailes
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My gosh! I could smack my fingers! I solved the problem by
1. Splitting the class in two. One to read and write and the other that is the class I want to store
2. By setting the fields in the class from the main method, not from inside the class. (long story on why i tried that...)

But it works now - horay and thanks for the help!

Rachel
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!