import java.io.*;
@SuppressWarnings("serial")
class Person implements Serializable {
public Person(String name, String sex, int age, int height) {
this.name = name;
this.sex = sex;
this.age = age;
this.height = height;
}
public String toString() {
return "|" + this.name + "|" + this.sex + "|" + this.age + "|"
+ this.height + "|";
}
public String name;
public String sex;
public int age;
public int height;
}
public class SerialTest {
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
Person p = new Person("Jim", "male", 28, 194);
// 开始序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
new File("myTest.txt")));
oos.writeObject(p);
// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File("myTest.txt")));
Person p1 = (Person) ois.readObject();
System.out.println(p1.toString());
}
}
Java 序列化反序列化文件
最新推荐文章于 2025-09-04 11:47:32 发布
本文介绍了一个简单的Java程序示例,演示了如何使用Java的序列化接口将一个包含人员基本信息的对象写入文件,以及如何从该文件中读取并还原这个对象。
4052

被折叠的 条评论
为什么被折叠?



