Serialization Utilities : Serialization « File Input Output « Java






Serialization Utilities

     


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationUtils {

    public static byte[] serialize(Object obj) {
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(buffer);
            oos.writeObject(obj);
            oos.close();
            return buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("error writing to byte-array!");
        }
    }

    public static Object deserialize(byte[] bytes)
            throws ClassNotFoundException {
        try {
            ByteArrayInputStream input = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(input);
            return ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("error reading from byte-array!");
        }
    }

    public static Object serializedCopy(Object obj) {
        try {
            return deserialize(serialize(obj));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("this shouldn't happen");
        }
    }

}

   
    
    
    
    
  








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.Serializer class
9.This program shows how to use getSerialVersionUID
10.Working with Serialization
11.Assists with the serialization process and performs additional functionality based on serialization.
12.Computes all the class serialVersionUIDs under the jboss home directory.
13.Serializable Enumeration
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.