这几天好好练习了一下对象流的序列化和反序列化的过程,其主要作用就是:
1. 序列化
主要是针对将在java中生成的对象经过加密后存入到自己电脑的硬盘上的某位置上,如果打开后,你会看到的是自己写入的对象都是乱码格式
2.反序列化
主要是将自己写到硬盘上的某个对象或者对象集合经过反序列的过程,重新经过解密后在IDE中进行读取和操作
首先需要创建一个需要保存的对象的类:该类需要实现***Serializable***此接口,其中该类的属性也是需要实现该接口的,我创建了一个学生类Student,代码如下:
`//学生类
class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String student_id;
private Integer student_age;
private String student_name;
public String getStudent_id() {
return student_id;
}
public void setStudent_id(String student_id) {
this.student_id = student_id;
}
public Integer getStudent_age() {
return student_age;
}
public void setStudent_age(Integer student_age) {
this.student_age = student_age;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public Student(String student_id, Integer student_age, String student_name) {
super();
this.student_id = student_id;
this.student_age = student_age;
this.student_name = student_name;
}
@Override
public String toString() {
return "Student [student_id=" + student_id + ", student_age=" + student_age + ", student_name=" + student_name
+ "]";
}
}
操作对象的类 即实现对象的序列化和反序列的代码如下:
@Test
public void TestObject() {
List<Student> list = new ArrayList<Student>();
//实现序列化-----即向硬盘中存储对象
for(int i = 0;i<10;i++) {
Student student = new Student("16100620" + i,(int)(Math.random()*10+10),"张三" + i);
list.add(student);
}
//写入对象操作------>序列化
ObjectOutputStream oos = null;
OutputStream os = null;
try {
os = new FileOutputStream("student.txt");
oos = new ObjectOutputStream(os);
oos.writeObject(list);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//读出硬盘中的对象----->反序列化操作
//读操作
List<Student> student_list = null;
InputStream is = null;
ObjectInputStream ois = null;
try {
is = new FileInputStream(new File("student.txt"));
ois = new ObjectInputStream(is);
student_list = (List<Student>)ois.readObject();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//使用迭代器进行遍历
Iterator it = student_list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//关流操作
if(oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ois != null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}