對(duì)象序列化存儲(chǔ)讀取實(shí)現(xiàn)代碼
1
import java.io.FileInputStream;
2
import java.io.FileOutputStream;
3
import java.io.ObjectInputStream;
4
import java.io.ObjectOutputStream;
5
import java.io.Serializable;
6
7
public class serialStore implements Serializable
{
8
9
public serialStore()
{
10
}// serialStore()
11
12
/** *//**
13
* 寫對(duì)象到指定文件中
14
*/
15
public void writeFile(String strFile, Object[] o)
{
16
try
{
17
FileOutputStream fos = new FileOutputStream(strFile);
18
ObjectOutputStream oos = new ObjectOutputStream(fos);
19
for (int i = 0; i < o.length; i++)
{
20
oos.writeObject(o[i]);
21
}
22
oos.flush();
23
} catch (Exception e)
{
24
e.printStackTrace();
25
}
26
}// writeFile()
27
28
/** *//**
29
* 讀指定文件的對(duì)象到對(duì)象組內(nèi)
30
*/
31
public Object[] readFile(String strFile, int objectNum)
{
32
Object o[] = new Object[objectNum];
33
try
{
34
FileInputStream fis = new FileInputStream(strFile);
35
ObjectInputStream ois = new ObjectInputStream(fis);
36
for (int i = 0; i < o.length; i++)
{
37
o[i] = ois.readObject();
38
}
39
} catch (Exception e)
{
40
e.printStackTrace();
41
}
42
return o;
43
}// readFile()
44
45
/** *//**
46
* 顯示對(duì)象內(nèi)容
47
*/
48
public void log(Object[] o)
{
49
for (int i = 0; i < o.length; i++)
{
50
System.out.println(o[i]);
51
}
52
}// log()
53
54
/** *//**
55
* 顯示對(duì)象內(nèi)容
56
*/
57
public void log(Object o)
{
58
System.out.println(o);
59
}// log()
60
61
public static void main(String arg[])
{
62
Object o[] = new Object[2];
63
o[0] = new String("objectName");
64
o[1] = new Integer(25);
65
serialStore ss = new serialStore();
66
String strFile = "serial.abc";
67
ss.writeFile(strFile, o);
68
ss.log(ss.readFile(strFile, o.length));
69
}//main()
70
71
}
72
/** *//** serialStore */
73
74

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


posted on 2005-11-09 10:03 bluesky 閱讀(456) 評(píng)論(0) 編輯 收藏 所屬分類: 基礎(chǔ)知識(shí)