how-to

Classes

How to serialize object instance into file stream

You can serialize object instance data into stream - in this case into file stream. It meams, save object instance into file for later reload.

STEP 1

First you must have class for serialization. This class must implements java.io.Serializable interface.

import java.io.Serializable;

public class Person implements Serializable {
          
  public Person() {}
      
  String name;
  int age;  
}

STEP 2

For serialization to file stream use this code:

/* -- create and fill object instance */

Person person = new Person();

person.name = "Jack Howard";
person.age = 35;

/* -- serialiaze object instance  to stream */

try {

  /* -- serialize object instance to file */

  ObjectOutputStream stream = new ObjectOutputStream( new FileOutputStream( "c:\\test.str" ) );

  /* -- write */

  stream.writeObject( person );

  /* -- close stream */

  stream.close();

} catch (FileNotFoundException ex) {
} catch (IOException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

Above code create file c:\test.str.

STEP 3

When you need deserialize data = load data from the stream and create again saved object instance(s), use this code:

try {

  /* -- create file stream for reading data */

  ObjectInputStream stream = new ObjectInputStream( new FileInputStream( "c:\\test.str" ) );

  /* -- read saved object instance */

  Person person = ( Person ) stream.readObject();

  /* -- write readed data */

  System.out.println( person.name );
  System.out.println( person.age );

  stream.close();

} catch ( IOException ex ) {
} catch ( ClassNotFoundException ex) {
  Logger.getLogger(Window.class.getName()).log( Level.SEVERE, null, ex );
}

The output will be:

Jack Howard
35