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);
}
}
-
3Please consider asking a real question, and describing which exact errors you get and from which lines.Arnaud– Arnaud2018-07-18 13:08:27 +00:00Commented Jul 18, 2018 at 13:08
-
1Ok sorry error on line number 23 r1=(rak) f9.readObject();rakshit ks– rakshit ks2018-07-18 13:16:53 +00:00Commented Jul 18, 2018 at 13:16
Add a comment
|
2 Answers
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);
Comments
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
Nikolas
Please, mark the best answer as accepted to let others know this issue has been resolved.
rakshit ks
The same thing worked for my friend who used netbeans ide for debugging.... How is that possible?
rakshit ks
And how to mark the best answer...I am new to stack overflow...I am newbie
Nikolas
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/…