1
|
package app;
|
2
|
|
3
|
import java.io.File;
|
4
|
import java.io.FileInputStream;
|
5
|
import java.io.FileOutputStream;
|
6
|
import java.io.IOException;
|
7
|
import java.io.ObjectInputStream;
|
8
|
import java.io.ObjectOutputStream;
|
9
|
|
10
|
public class App
|
11
|
{
|
12
|
|
13
|
/**
|
14
|
* When the Serialized and deserialized classes are same, but placed in diff
|
15
|
* packages, the deserialization does not work.
|
16
|
* When they are
|
17
|
* **/
|
18
|
public static void main(String[] args) throws Exception
|
19
|
{
|
20
|
try{
|
21
|
System.out.println("Starting...");
|
22
|
|
23
|
App thisApp = new App();
|
24
|
//thisApp.Serialize(new SampleClassesOK.Simple(), "serialized/simple.out");
|
25
|
|
26
|
SampleClassesOK.Simple test1 = thisApp.Deserialize("serialized/simple.out");
|
27
|
|
28
|
}catch(Exception e)
|
29
|
{
|
30
|
System.out.println(e.toString());
|
31
|
System.out.println(e.getMessage());
|
32
|
}
|
33
|
}
|
34
|
|
35
|
private <T> T Deserialize(String inputFilePath)
|
36
|
{
|
37
|
try
|
38
|
{
|
39
|
FileInputStream fis = new FileInputStream(inputFilePath);
|
40
|
ObjectInputStream ois = new ObjectInputStream(fis);
|
41
|
T deserialized = (T) ois.readObject();
|
42
|
System.out.println(deserialized.toString());
|
43
|
ois.close();
|
44
|
|
45
|
return deserialized;
|
46
|
}
|
47
|
catch (IOException e)
|
48
|
{
|
49
|
e.printStackTrace();
|
50
|
}
|
51
|
catch (ClassNotFoundException e)
|
52
|
{
|
53
|
e.printStackTrace();
|
54
|
}
|
55
|
return null;
|
56
|
}
|
57
|
|
58
|
/**
|
59
|
* Standard way of serializing objects with java.
|
60
|
*
|
61
|
* Taken from example method, doc
|
62
|
**/
|
63
|
private void Serialize(Object obj, String outputPath)
|
64
|
{
|
65
|
try
|
66
|
{
|
67
|
File toWrite = new File(outputPath);
|
68
|
toWrite.createNewFile();
|
69
|
|
70
|
FileOutputStream fos = new FileOutputStream(toWrite, false);
|
71
|
ObjectOutputStream oos = new ObjectOutputStream(fos);
|
72
|
|
73
|
oos.writeObject(obj);
|
74
|
oos.flush();
|
75
|
oos.close();
|
76
|
System.out.println("serialized.");
|
77
|
}
|
78
|
catch (Exception e)
|
79
|
{
|
80
|
e.printStackTrace();
|
81
|
}
|
82
|
}
|
83
|
}
|