进阶day10-序列化流的练习
This commit is contained in:
@@ -11,7 +11,8 @@ public class Student implements Serializable {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 7268053700279080345L;//字节码文件的版本号
|
||||
String name;
|
||||
transient int age;//transient:瞬态,在序列化对象时,被它修饰的属性,不能被保存
|
||||
//transient int age;//transient:瞬态,在序列化对象时,被它修饰的属性,不能被保存
|
||||
int age;
|
||||
|
||||
static String classroom = "1903";//不会被序列化,静态内容跟着字节码文件,只跟类有关
|
||||
|
||||
@@ -24,4 +25,11 @@ public class Student implements Serializable {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Student{" +
|
||||
"name='" + name + '\'' +
|
||||
", age=" + age +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
41
javaSE-day10/src/com/inmind/object_stream03/Test13.java
Normal file
41
javaSE-day10/src/com/inmind/object_stream03/Test13.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.inmind.object_stream03;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。
|
||||
2. 反序列化list.txt ,并遍历集合,打印对象信息。
|
||||
*/
|
||||
public class Test13 {
|
||||
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
||||
//创建集合保存学生对象
|
||||
ArrayList<Student> students = new ArrayList<>();
|
||||
students.add(new Student("张三", 18));
|
||||
students.add(new Student("李四", 20));
|
||||
students.add(new Student("王五", 19));
|
||||
|
||||
//序列化保存集合
|
||||
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
|
||||
oos.writeObject(students);
|
||||
oos.close();
|
||||
|
||||
//创建反序列化流对象
|
||||
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));
|
||||
Object o = ois.readObject();
|
||||
ArrayList objs = null;
|
||||
if (o instanceof ArrayList) {
|
||||
objs = (ArrayList) o;
|
||||
}
|
||||
|
||||
//遍历集合,打印对象信息。
|
||||
for (Object obj : objs) {
|
||||
if (obj instanceof Student) {
|
||||
Student s = (Student) obj;
|
||||
System.out.println(s.name);
|
||||
System.out.println(s.age);
|
||||
System.out.println(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user