package ru rpod taop import java io FileInputStream import java io Fil

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package ru.rpod.taop;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Random;
class Data implements Serializable{
private int n;
public Data(int n) {
this.n = n;
}
public String toString(){
return Integer.toString(n);
}
}
public class Worm implements Serializable{
private static Random rand = new Random(47);
private Data[] data = {
new Data(rand.nextInt(10)),
new Data(rand.nextInt(10)),
new Data(rand.nextInt(10)),
};
private Worm next;
private char c;
public Worm(int i, char x){
System.out.println("Worm's constructor: "+i);
c=x;
if(--i>0)
next = new Worm(i, (char)(x+1));
}
public Worm(){
System.out.println("Worm's default constructor");
}
public String toString(){
//чтобы вывод был красивым :-)
StringBuilder result = new StringBuilder(":");
result.append(c);
result.append("(");
for(Data dat : data)
result.append(dat);
result.append(")");
if(next!=null)result.append(next);
return result.toString();
}
/**
* @param args
*/
public static void main(String[] args) throws ClassNotFoundException, IOException{
Worm w = new Worm(6, 'a');
System.out.println("w = " +w);
//сериализуем в файл
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worm.out"));
out.writeObject("Worm storage\n");
out.writeObject(w);
out.close();
//десериализация из файла
ObjectInputStream in = new ObjectInputStream(new FileInputStream("worm.out"));
String s = (String)in.readObject();
Worm w2=(Worm)in.readObject();
System.out.println(s +"w2 = " +w2);
}
}