package com.itheima.convertedio;
import java.io.*;
import java.util.ArrayList;
public class ConverteDemo6 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1=new Student("杜子腾",16);
Student s2=new Student("张三",23);
Student s3=new Student("李四",24);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(".\\a.txt"));
/* oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);*/
ArrayList<Student> list=new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
oos.writeObject(list);
oos.close();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(".\\a.txt"));
Object obj;
/*while ((obj=ois.readObject())!=null){
System.out.println(obj);
}*/
/*while (true){
try {
Object o = ois.readObject();
System.out.println(o);
} catch (EOFException e){
break;
}
}*/
ArrayList<Student> list2 =(ArrayList<Student>) ois.readObject();
for (Student student : list) {
System.out.println(student);
}
ois.close();
}
}
package com.itheima.convertedio;
import java.io.Serializable;
public class Student implements Serializable {
//序列化编号
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
|