forked from dahogn/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassIODemo.java
More file actions
98 lines (83 loc) · 2.55 KB
/
Copy pathClassIODemo.java
File metadata and controls
98 lines (83 loc) · 2.55 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cn.sdu.edu.sc.java.chapt10;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import cn.sdu.edu.sc.java.chapt6.Student;
/**
* 说明对象的二进制读取和写入方法
*
* @author Dahogn
* @version 1.01
* @since 2008.12.10
*/
public class ClassIODemo {
public static void main(String[] args) {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(
"Student.records"));
} catch (IOException e) {
System.out
.println("Error opening file Student.records for writing.");
System.exit(0);
}
// Student类或者其父类必须已经 implements Serializable
// 如果使用父类中定义的属性,父类必须implements Serializable
Student oneRecord = new Student("Calif", 27);
Student secondRecord = new Student("Black", 100);
Student[] studlist = new Student[2];
studlist[0] = oneRecord;
studlist[1] = secondRecord;
try {
// 直接将一个对象写入到文件
outputStream.writeObject(studlist);
outputStream.writeObject(oneRecord);
outputStream.writeObject(secondRecord);
} catch (IOException e) {
System.out.println("Error writing to file Student.records.");
System.exit(0);
} finally {
try {
outputStream.close();
} catch (IOException e) {
System.out.println("Problem with close the stream");
}
}
System.out.println("Records sent to file Student.record.");
System.out.println("Now let's re-open the file and echo the records.");
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream(
"Student.records"));
} catch (IOException e) {
System.out.println("Error opening file Student.records.");
System.out.println("for reading.");
System.exit(0);
}
Student readOne = null, readTwo = null;
Student[] studlistAG = null;
try {
studlistAG = (Student[]) inputStream.readObject();
readOne = (Student) inputStream.readObject();
readTwo = (Student) inputStream.readObject();
} catch (Exception e) {
System.out.println("Error reading from file Student.records.");
System.exit(0);
} finally {
try {
inputStream.close();
} catch (IOException e) {
System.out.println("Problem with close the stream");
}
}
System.out.println("The following were read\n"
+ "from the file Student.record:");
System.out.println(studlistAG[0]);
System.out.println(studlistAG[1]);
System.out.println(readOne);
System.out.println(readTwo);
System.out.println("End of program.");
}
}