Tuesday, December 26, 2017

JAVA - How to serialize object instance into file stream

You can serialize object instance data into stream - in this scenario into file stream. It means, save object instance into file for later reloading.

STEP 1
First you must prepare 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 created file c:\test.str.
STEP 3
When you need de-serialize 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 );
}
Output:
Jack Howard
35

No comments:

Post a Comment