Serializer class : Serialization « File Input Output « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » File Input Output » Serialization 




Serializer class
      
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.Serializable;

/**
 * This class defines utility routines that use Java serialization.
 */
public class Serializer {
  /**
   * Serialize the object o (and any Serializable objects it refers to) and
   * store its serialized state in File f.
   */
  static void store(Serializable o, File fthrows IOException {
    ObjectOutputStream out = // The class for serialization
    new ObjectOutputStream(new FileOutputStream(f));
    out.writeObject(o)// This method serializes an object graph
    out.close();
  }

  /**
   * Deserialize the contents of File f and return the resulting object
   */
  static Object load(File fthrows IOException, ClassNotFoundException {
    ObjectInputStream in = // The class for de-serialization
    new ObjectInputStream(new FileInputStream(f));
    return in.readObject()// This method deserializes an object graph
  }

  /**
   * Use object serialization to make a "deep clone" of the object o. This
   * method serializes o and all objects it refers to, and then deserializes
   * that graph of objects, which means that everything is copied. This
   * differs from the clone() method of an object which is usually implemented
   * to produce a "shallow" clone that copies references to other objects,
   * instead of copying all referenced objects.
   */
  static Object deepclone(final Serializable othrows IOException,
      ClassNotFoundException {
    // Create a connected pair of "piped" streams.
    // We'll write bytes to one, and them from the other one.
    final PipedOutputStream pipeout = new PipedOutputStream();
    PipedInputStream pipein = new PipedInputStream(pipeout);

    // Now define an independent thread to serialize the object and write
    // its bytes to the PipedOutputStream
    Thread writer = new Thread() {
      public void run() {
        ObjectOutputStream out = null;
        try {
          out = new ObjectOutputStream(pipeout);
          out.writeObject(o);
        catch (IOException e) {
        finally {
          try {
            out.close();
          catch (Exception e) {
          }
        }
      }
    };
    writer.start()// Make the thread start serializing and writing

    // Meanwhile, in this thread, read and deserialize from the piped
    // input stream. The resulting object is a deep clone of the original.
    ObjectInputStream in = new ObjectInputStream(pipein);
    return in.readObject();
  }

  /**
   * This is a simple serializable data structure that we use below for
   * testing the methods above
   */
  public static class DataStructure implements Serializable {
    String message;

    int[] data;

    DataStructure other;

    public String toString() {
      String s = message;
      for (int i = 0; i < data.length; i++)
        s += " " + data[i];
      if (other != null)
        s += "\n\t" + other.toString();
      return s;
    }
  }

  /** This class defines a main() method for testing */
  public static class Test {
    public static void main(String[] argsthrows IOException,
        ClassNotFoundException {
      // Create a simple object graph
      DataStructure ds = new DataStructure();
      ds.message = "hello world";
      ds.data = new int[] { 123};
      ds.other = new DataStructure();
      ds.other.message = "nested structure";
      ds.other.data = new int[] { 98};

      // Display the original object graph
      System.out.println("Original data structure: " + ds);

      // Output it to a file
      File f = new File("datastructure.ser");
      System.out.println("Storing to a file...");
      Serializer.store(ds, f);

      // Read it back from the file, and display it again
      ds = (DataStructureSerializer.load(f);
      System.out.println("Read from the file: " + ds);

      // Create a deep clone and display that. After making the copy
      // modify the original to prove that the clone is "deep".
      DataStructure ds2 = (DataStructureSerializer.deepclone(ds);
      ds.other.message = null;
      ds.other.data = null// Change original
      System.out.println("Deep clone: " + ds2);
    }
  }
}

           
         
    
    
    
    
    
  














Related examples in the same category
1.Serialization with ObjectInputStream and ObjectOutputStream
2.Object SerializationObject Serialization
3.Serial Demo
4.Create a serialized output file
5.Reconstructing an externalizable objectReconstructing an externalizable object
6.Simple use of Externalizable and a pitfallSimple use of Externalizable and a pitfall
7.Serializable
8.This program shows how to use getSerialVersionUID
9.Working with Serialization
10.Assists with the serialization process and performs additional functionality based on serialization.
11.Computes all the class serialVersionUIDs under the jboss home directory.
12.Serializable Enumeration
13.Serialization Utilities
14.This program demonstrates the transfer of serialized objects between virtual machines
15.A class whose clone method uses serialization
16.Writes a serialized version of obj to a given file, compressing it using gzip.
17.Reads a serialized object from a file that has been compressed using gzip.
18.Serialized File Util
19.Serializes an object to a file, masking out annoying exceptions.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.