hi i'm learing Object Serialization and tried this
import java.io.*;
class Employee implements Serializable{
Employee(int temp_id,String temp_name)
{
id=temp_id;
name=temp_name;
}
int id;
String name;
}
public class SerialTest{
public static void main(String[] args)
{
Employee e1=new Employee(14,"John");
try{
FileOutputStream fileStream=new FileOutputStream("myserial.ser");
ObjectOutputStream os=new ObjectOutputStream(fileStream);
os.writeObject(e1);
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
finally{
os.close();
}
}//main ends
}//class ends
The program worked before i put in the call to
os.close();
Now i doesn't compile , i get the error saying
SerialTest.java:29: cannot find symbol
symbol : variable os
location: class SerialTest
os.close();
^
It worked before i tried to close the ObjectOutPutStream , the contents of the serialized file are below ,
¬í^@^Esr^@^HEmployee^S<89>S§±<9b>éØ^B^@^BI^@^BidL^@^Dnamet^@^RLjava/lang/String;xp^@^@^@^Nt^@^GSainath
~
i cant seem to understand where i am going wrong , please help!
You want to use the purpose-built try-with-resources:
try (ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("myserial.ser"));) {
os.writeObject(e1);
} catch(IOException ioex) {
ioex.printStackTrace();
}