1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package p3j.misc;
17
18 import java.beans.XMLDecoder;
19 import java.beans.XMLEncoder;
20 import java.io.BufferedInputStream;
21 import java.io.BufferedOutputStream;
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 import java.io.OutputStream;
29 import java.util.zip.GZIPInputStream;
30 import java.util.zip.GZIPOutputStream;
31
32
33
34
35
36
37
38
39
40
41
42
43 public class Serializer {
44
45
46
47
48
49 private boolean usingXML;
50
51
52
53
54 private boolean useCompression = true;
55
56
57
58
59
60
61
62
63
64
65
66
67 public Object load(String file) throws IOException, ClassNotFoundException {
68 if (usingXML) {
69 return loadFromXML(file);
70 }
71 return loadFromBinary(file);
72 }
73
74
75
76
77
78
79
80
81
82
83
84
85 public Object loadFromBinary(String file) throws IOException,
86 ClassNotFoundException {
87 ObjectInputStream input = new ObjectInputStream(getInputStream(file));
88 Object o = input.readObject();
89 input.close();
90 return o;
91 }
92
93
94
95
96
97
98
99
100
101
102 public Object loadFromXML(String file) throws IOException {
103 XMLDecoder xmlDecoder = new XMLDecoder(getInputStream(file));
104 Object object = xmlDecoder.readObject();
105 xmlDecoder.close();
106 return object;
107 }
108
109
110
111
112
113
114
115
116
117
118 protected InputStream getInputStream(String file) throws IOException {
119 InputStream in = new BufferedInputStream(new FileInputStream(file));
120 if (useCompression) {
121 in = new GZIPInputStream(in);
122 }
123 return in;
124 }
125
126
127
128
129
130
131
132
133
134
135 protected OutputStream getOutputStream(String file) throws IOException {
136 OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
137 if (useCompression) {
138 out = new GZIPOutputStream(out);
139 }
140 return out;
141 }
142
143
144
145
146
147
148
149
150
151
152
153 public void save(Object object, String file) throws IOException {
154 if (usingXML) {
155 saveToXML(object, file);
156 } else {
157 saveToBinary(object, file);
158 }
159 }
160
161
162
163
164
165
166
167
168
169
170
171 public void saveToBinary(Object object, String file) throws IOException {
172 ObjectOutputStream output = new ObjectOutputStream(getOutputStream(file));
173 output.writeObject(object);
174 output.close();
175 }
176
177
178
179
180
181
182
183
184
185
186
187 public void saveToXML(Object object, String file) throws IOException {
188 XMLEncoder xmlEncoder = new XMLEncoder(getOutputStream(file));
189 xmlEncoder.writeObject(object);
190 xmlEncoder.close();
191 }
192
193 public boolean isUsingXML() {
194 return usingXML;
195 }
196
197 public void setUsingXML(boolean usingXML) {
198 this.usingXML = usingXML;
199 }
200
201 }