1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.jameleon.util;
20
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
28
29 public class InstanceSerializer{
30
31 private InstanceSerializer(){}
32 /***
33 * The file extension for serialized files
34 */
35 public static final String SERIALIZED_EXT = ".dat";
36
37 /***
38 * Serializes a given object to a given file.
39 * @param obj - the object to serialize
40 * @param file - the file to serialize the object to
41 * @throws IOException if the file can't be serialized
42 */
43 public static void serialize(Object obj, File file) throws IOException{
44 ObjectOutputStream s = null;
45 if (file.getParentFile() != null) {
46 JameleonUtility.createDirStructure(file.getParentFile());
47 }
48 try{
49 s = new ObjectOutputStream(new FileOutputStream(file));
50 s.writeObject(obj);
51 s.flush();
52 }finally{
53 if (s != null) {
54 s.close();
55 }
56 }
57 }
58
59 /***
60 * Deserializes an object from a given file name
61 * @param fileName - A String representing the location of the serialized file
62 * @throws IOException - If the file can not be deserialzed
63 * @throws ClassNotFoundException - If a class corresponding to the serialized file
64 * is not in the Classpath
65 */
66 public static Object deserialize(String fileName) throws IOException, ClassNotFoundException{
67 return deserialize(new FileInputStream(fileName));
68 }
69
70 /***
71 * Deserializes an object from a given InputStream
72 * @param in - An InputStream representing a serialized file.
73 * @throws IOException - If the file can not be deserialzed
74 * @throws ClassNotFoundException - If a class corresponding to the serialized file
75 * is not in the Classpath
76 */
77 public static Object deserialize(InputStream in) throws IOException, ClassNotFoundException{
78 Object obj = null;
79 ObjectInputStream s = null;
80 if (in != null) {
81 try{
82 s = new ObjectInputStream(in);
83 obj = s.readObject();
84 }finally{
85 if (s != null) {
86 s.close();
87 }
88 }
89 }
90 return obj;
91 }
92
93 }