- java的序列化是将对象写入到文本中
- 首先需要一个类,必须实现Serializable接口
class Person implements Serializable{
//如果这个属性不想被序列化就加上transient
transient int age;
String name;
}
//写入
FileOutputStream fileOut = new FileOutputStream("out.txt");
ObjectOutputStream stream = new ObjectOutputStream(fileOut);
Person p = new Person();
p.age = 12;
p.name = "张三";
stream.writeObject(p);
stream.close();
fileOut.close();
//读取出来
FileInputStream file = new FileInputStream("out.txt");
ObjectInputStream stream = new ObjectInputStream(file);
Object object = stream.readObject();
Person p = (Person)object;
System.out.println("name = " + p.name);
System.out.println("age = " + p.age);
stream.close();
file.close();
网友评论