View Javadoc

1   package org.sf.jlaunchpad.util;
2   
3   import java.io.*;
4   
5   /**
6    * This class contains convenient methods for serializing/deserializing objects.
7    *
8    * @author Alexander Shvets
9    * @version 1.0 12/16/2006
10   */
11  public class SerializableUtil {
12  
13    /**
14     * Serializes the object.
15     *
16     * @param object the object to be serialized
17     *
18     * @return object in form ob array of bytes
19     * @throws IOException exception
20     */
21    public static byte[] serialize(Object object) throws IOException {
22      byte[] bytes = new byte[0];
23  
24      if(object != null) {
25        ByteArrayOutputStream baos = new ByteArrayOutputStream();
26        ObjectOutputStream oos = null;
27        try {
28          oos = new ObjectOutputStream(baos);
29  
30          oos.writeObject(object);
31  
32          bytes = baos.toByteArray();
33        }
34        finally {
35          if(oos != null) {
36            oos.close();
37          }
38        }
39      }
40  
41      FileUtil.copyToFile(new ByteArrayInputStream(bytes), new File("c:/test.class"));
42  
43      return bytes;
44    }
45  
46    /**
47     * Deserializes the object.
48     *
49     * @param bytes object in form ob array of bytes
50     * @return the deserialized object
51     * @throws IOException exception
52     * @throws ClassNotFoundException exception 
53     */
54    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
55      Object object = null;
56  
57      ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
58      ObjectInputStream ois = null;
59      try {
60        ois = new ObjectInputStream(bais);
61  
62        object = ois.readObject();
63      }
64      finally {
65        if(ois != null) {
66          ois.close();
67        }
68      }
69  
70      return object;
71    }
72  
73  }