-5
import java.io.*;

class rak implements Serializable{

    int i;
}

public class Main {

    public static void main(String[] args) throws Exception {
        // write your code herer
        rak r = new rak();
        r.i = 9;

        File f = new File("da.txt");
        FileOutputStream f1 = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(f1);
        oos.writeObject("value of  i is" + r.i);

        FileInputStream f0 = new FileInputStream(f);
        ObjectInputStream f9 = new ObjectInputStream(f0);
        rak r1 = new rak();
        r1 = (rak) f9.readObject();

        System.out.println(r1.i);

    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
rakshit ks
  • 422
  • 5
  • 13

2 Answers2

2

You serialize a String :

rak r = new rak();
...
oos.writeObject("value of  i is" + r.i);

And you cast the deserialization result into a rak object :

r1 = (rak) f9.readObject();

Whereas the ClassCastException : a String is not a rak.

If you want to deserialize a rak, serialize it and not only one of its fields such as :

oos.writeObject(r);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

At this line:

oos.writeObject("value of  i is" + r.i);

You serialize the String "value of i is9" literally instead of the object itself. Thus the only possible cast is to the String again.

String string = (String) f9.readObject();

To fix this issue, serialize the whole object:

rak r = new rak();
r.i = 9;
// ...
oos.writeObject(r);

And the result of the last line would be correct:

// ...
rak r1 =  (rak) f9.readObject();
System.out.println(r1.i);          // prints 9
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183