1 |
package appl.data; |
2 |
|
3 |
import java.io.BufferedInputStream; |
4 |
import java.io.BufferedOutputStream; |
5 |
import java.io.File; |
6 |
import java.io.FileInputStream; |
7 |
import java.io.FileNotFoundException; |
8 |
import java.io.FileOutputStream; |
9 |
import java.io.ObjectInputStream; |
10 |
import java.io.ObjectOutputStream; |
11 |
|
12 |
/** |
13 |
* @author Dominik Appl |
14 |
*/ |
15 |
public class SerializedDataLoader implements DataLoader { |
16 |
|
17 |
protected File loadFile; |
18 |
|
19 |
private boolean del_after_loading; |
20 |
|
21 |
private SerializedDataLoader() { |
22 |
} |
23 |
|
24 |
public SerializedDataLoader(File loadFile, |
25 |
boolean DELETE_SOURCE_AFTER_LOADING) { |
26 |
this.loadFile = loadFile; |
27 |
del_after_loading = DELETE_SOURCE_AFTER_LOADING; |
28 |
} |
29 |
|
30 |
public SerializedDataLoader(File loadFile) { |
31 |
this(loadFile, false); |
32 |
} |
33 |
|
34 |
/* |
35 |
* (non-Javadoc) |
36 |
* |
37 |
* @see appl.data.DataLoader#load() |
38 |
*/ |
39 |
public Object load() throws LoadingException { |
40 |
Object loadedObject = null; |
41 |
try { |
42 |
BufferedInputStream fis = new BufferedInputStream( |
43 |
new FileInputStream(loadFile)); |
44 |
ObjectInputStream ois = new ObjectInputStream(fis); |
45 |
loadedObject = ois.readObject(); |
46 |
ois.close(); |
47 |
fis.close(); |
48 |
// remove File from Filesystem |
49 |
if (del_after_loading) |
50 |
loadFile.delete(); |
51 |
|
52 |
} catch (FileNotFoundException e) { |
53 |
throw new LoadingException("Could not find temporary unload-file:" |
54 |
+ loadFile, loadFile); |
55 |
|
56 |
} catch (Exception e) { |
57 |
e.printStackTrace(); |
58 |
throw new LoadingException("Could not load from temporary file " |
59 |
+ loadFile, loadFile); |
60 |
|
61 |
} |
62 |
return loadedObject; |
63 |
|
64 |
} |
65 |
|
66 |
public static void SerializeToFile(Object o, File destFile) |
67 |
throws LoadingException { |
68 |
try { |
69 |
destFile.createNewFile(); |
70 |
BufferedOutputStream fos = new BufferedOutputStream( |
71 |
new FileOutputStream(destFile)); |
72 |
ObjectOutputStream oos = new ObjectOutputStream(fos); |
73 |
oos.writeObject(o); |
74 |
oos.close(); |
75 |
fos.close(); |
76 |
} catch (Exception e) { |
77 |
e.printStackTrace(); |
78 |
} |
79 |
|
80 |
} |
81 |
|
82 |
/* |
83 |
* (non-Javadoc) |
84 |
* |
85 |
* @see appl.data.DataLoader#getLoadInfo() |
86 |
*/ |
87 |
public String getLoadInfo() { |
88 |
return "SerializedDataLoader|" + loadFile.getPath(); |
89 |
} |
90 |
|
91 |
} |