1

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!

Sainath S.R
  • 3,074
  • 9
  • 41
  • 72
  • 4
    You should read about what *variable scope* is. Also check try-with-resources. – Pshemo Oct 18 '14 at 11:30
  • 1
    oh! , are objects in try {//object declaration} limited within the try block? – Sainath S.R Oct 18 '14 at 11:32
  • 1
    You are 99% correct, because it is not objects that are limited to scope, but variables (references). Because of this you need to create reference before `try` blocks if you want to use it outside of `try` (like in `catch` or `finally`). You can set this reference to `null` and change its value in `try`. You can let compiler handle it automatically by using [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – Pshemo Oct 18 '14 at 11:35
  • Ok ! , i get it , thanks for the clear answer and I also checked try with , seems to be a very useful addition to Java SE:7 ,. – Sainath S.R Oct 18 '14 at 11:37

1 Answers1

3

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();
    }
rolfl
  • 17,539
  • 7
  • 42
  • 76