Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Write/Persist an object

Now write you serialized object Employee into a binary file

Program :

Step 1 - Coding

Create a text file c:/sunilos/TestWriteEmployee.java and copy below contents.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


 * A program to write in persist data file implemented Serializable interface.
public class TestWriteEmployee {

    public static void main(String[] args) throws Exception{
        FileOutputStream fileOutputStream = new FileOutputStream("c:/sunilos/sunilos.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
        Employee emp = new Employee(1,"Sunil","OS");
        System.out.println("Obiect is successfully presisted");



Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestWriteEmployee.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestWriteEmployee.java with help of 
    • javac TestWriteEmployee.java command. Command will create TestWriteEmployee.class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestWriteEmployee command.
  3. It will create file and object will be stored in
    • c:/sunilos/sunilos.ser


Obiect is successfully presisted

NOTE : transient variables do not persist during object serialization or transient variables are discarded during serialization.

Go to next program to read(deserialize) an object..

<<Previous | Next>>

Prachi Pacharne,
Oct 16, 2015, 7:14 AM