File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Serialization question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Serialization question" Watch "Serialization question" New topic

Serialization question

Marx Villegas
Ranch Hand

Joined: Mar 10, 2006
Posts: 94
Hi! I'm studying for the SCJP exam using the great Sierra/Bates book...
And... Well, I tried to replicate some serialization code examples and it does not work as expected... here's the code:


class NsClass {
int i;

public void setI(int i) {
this.i = i;

public int getI(){
return this.i;

public class SerialTest extends NsClass implements Serializable{
String myVar;

public void writeObject (ObjectOutputStream oos) throws IOException, ClassNotFoundException {

public void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException {

public static void main(String [] args) {

SerialTest s1 = new SerialTest();
SerialTest s2;
s1.myVar = "this is my var...";

//write object
try {
FileOutputStream fos = new FileOutputStream("fos.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);

//Read written object
FileInputStream fis = new FileInputStream("fos.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
s2 = (SerialTest)ois.readObject();
System.out.println("Reading s2 var..." + s2.myVar);
System.out.println("Reading i var..." + s2.i);
catch (Exception ex) {
System.out.println("Exception " + ex.toString());


The thing is that in this custom serialization the variable i is not getting saved into the file fos.txt, so when I deserialize it and print it the result is:

Reading s2 var...this is my var...
Reading i var...0

What am I doing wrong?
Please help...
Thanks in advance

When the compiler's not happy, ain't nobody happy...
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
As it is your writeObject and readObject methods aren't being called because they have the wrong method signitures. Change the access specifiers on your writeObject & readObject methods to private and it will work.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Marx Villegas
Ranch Hand

Joined: Mar 10, 2006
Posts: 94
That explains everything...
Thanks a lot
I agree. Here's the link:
subject: Serialization question
It's not a secret anymore!