This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes About serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About serialization" Watch "About serialization" New topic
Author

About serialization

C Law
Greenhorn

Joined: Mar 05, 2006
Posts: 21
I'm not sure I understand how the state of an object is preserved.

For one thing:

Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

What is test.ser? Is it an actual file? How can I found it?

Secondly, it seems that I can modify instance variable after
the object containing it has been serialized:

public class Animal{
String name = "Mutsang";

public static void main(String[] argv){
Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

a.name = "Tiger";

try{
FileInputStream fi = new FileInputStream("test.ser");
ObjectInputStream oo = new ObjectInputStream(fi);
oo.readObject();
System.out.println(a.name);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}
//output is Tiger.

If the state is really saved in "test.ser", how come that when
the object is restored, its "name" field is changed?

Thanks in advance!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18507
    
  40

Hint: When you run this command...



What do you think happens to the object that is returned?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About serialization
 
Similar Threads
Serializable problem
serialized ArrayList object
Getting error while serializing. Please see the following code while produces IOException.
Inner class & serialize
How it works when we implement writeObject and readObject