• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in Serialization?

 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I want to store objects of "User Class " in a text file called "users.txt". But I'm facing a small problem at the moment .That is when Im'm writing object to the file the existing objects get replaced by new ones .So finally my file contains only one object which i entered last .How to get rid of this case .



This is my user class. I'm creating three user objects in my Main class.But Finally I can see only one object in this text file. Please help ! I'm new to serialization. And little bit confused about its usage.
 
Rok Štelcer
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

This is expected behavior according to your code.
All you need to do:
change to:
This should do the trick.


Regards,
Rok
 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rok Thanks for your kind help ! But after doing that I tried to read a object using



But again I get the username of the last object i entered. does readObject() method reads objects from last entered to first entered?

And Please help me with a way to read all the objects in the file ? I mean do I have to use a for loop or something ? or is there another way ?
 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually what i want to know is how to deserialize multiple objects in a serialized file? Thanks !
 
Rok Štelcer
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please find a dummy example for saving / restoring:
And the output:
C:\Program Files\Java\jdk1.6.0_17\bin>javac Test.java & java Test
Test read = Test
Username = user1
Password = passwd1
UserType = type1

Test read = Test
Username = user2
Password = passwd2
UserType = type2

Test read = Test
Username = user3
Password = passwd3
UserType = type3

lakmal padmakumara wrote:Actually what i want to know is how to deserialize multiple objects in a serialized file? Thanks !

That's the downside of a binary file.
You exactly have to now its structure.
For example:
If you store three diff objects, like:
A, B & C,
you'll have to read them in exactly the same sequence.
That is: A, B & C.

Hope this helps.


Regards,
Rok
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic