序列化就是利用ObjectOutputStream与FileOutputStream之间的联系将数据写入文本中;
反序列化是利用ObjectInputStream与FileInputStream之间的联系将数据读出来,已实体类的方式接受。
一个Student对象的序列化:
package liu;
import java.io.Serializable;
/**
* 实体类pojo
* Created by Administrator on 2017/9/1.
*/
public class Student implements Serializable {
private static final long serializUID= -1888888888L;
String name ;
int id;
transient int age;
String department;
public Student() {
}
public Student(String name, int id, int age, String department) {
this.name = name;
this.id = id;
this.age = age;
this.department = department;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
", department='" + department + '\'' +
'}';
}
}
package liu;
import java.io.*;
/**
* 序列化
* Created by Administrator on 2017/9/1.
*/
public class StudentXLH {
//对实体类进行序列化
private static void SerializeStudent() throws Exception{
Student s = new Student();
s.name="马云";
s.age=21;
s.id=138;
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("aaa.txt")));//序列化信息放在文本中
oos.writeObject(s);
System.out.println("序列化成功!");
}
//反序列化为实体类
private static void FanSerializeStudent() throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aaa.txt"));
Student student = (Student) ois.readObject();
System.out.println("姓名:"+student.name+",年龄:"+student.age);
}
public static void main(String[] args) throws Exception{
SerializeStudent();
FanSerializeStudent();
}
}


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



