-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);

    }
}
2
  • 3
    Please consider asking a real question, and describing which exact errors you get and from which lines. Commented Jul 18, 2018 at 13:08
  • 1
    Ok sorry error on line number 23 r1=(rak) f9.readObject(); Commented Jul 18, 2018 at 13:16

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Please, mark the best answer as accepted to let others know this issue has been resolved.
The same thing worked for my friend who used netbeans ide for debugging.... How is that possible?
And how to mark the best answer...I am new to stack overflow...I am newbie
You choose the best one and click to the “mark” symbol on the left side of the answer. It will change color to green. meta.stackexchange.com/questions/5234/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.