📄 serializetest.java
字号:
import java.io.*;
class SerializeTest
{
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException
{
Student s1 = new Student(1, "zhangshan", 98.5);
Student s2 = new Student(2, "lisi", 96.5);
Student s3 = new Student(3, "wangwu", 90.5);
FileOutputStream fos = new FileOutputStream("Student2.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.close();
FileInputStream fis = new FileInputStream("Student2.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s;
for (int i=0; i<3; i++)
{
s = (Student)ois.readObject();
System.out.println(s.num + ":" + s.name + ":" + s.score);
}
ois.close();
}
}
class Student implements Serializable
{
int num;
String name;
double score;
Student(int num, String name, double score)
{
this.num = num;
this.name = name;
this.score = score;
}
private void writeObject(ObjectOutputStream oos) throws IOException
{
System.out.println("Object write");
oos.writeInt(num);
oos.writeUTF(name);
//System.out.println("Object write");
}
private void readObject(ObjectInputStream ois) throws IOException
{
System.out.println("Object read");
num = ois.readInt();
name = ois.readUTF();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -