• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Deserializing objects

 
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
 
Bartender
Posts: 9615
16
Mac OS X Linux 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
 
Crusading Chameleon likes the size of this ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
    Bookmark Topic Watch Topic
  • New Topic