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);
}
}
Asked
Active
Viewed 2,431 times
-5

khelwood
- 55,782
- 14
- 81
- 108

rakshit ks
- 422
- 5
- 13
-
3Please consider asking a real question, and describing which exact errors you get and from which lines. – Arnaud Jul 18 '18 at 13:08
-
1Ok sorry error on line number 23 r1=(rak) f9.readObject(); – rakshit ks Jul 18 '18 at 13:16
2 Answers
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
-
Please, mark the best answer as accepted to let others know this issue has been resolved. – Nikolas Charalambidis Jul 18 '18 at 14:12
-
The same thing worked for my friend who used netbeans ide for debugging.... How is that possible? – rakshit ks Jul 18 '18 at 16:58
-
And how to mark the best answer...I am new to stack overflow...I am newbie – rakshit ks Jul 18 '18 at 17:00
-
You choose the best one and click to the “mark” symbol on the left side of the answer. It will change color to green. https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Nikolas Charalambidis Jul 18 '18 at 18:34