从对象流中读取若干对象(tips:若不确定对象个数可以放入ArrayList中,强行读取可能会报错)
反序列流读取时要强转为ArrayList
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String address;
public Student() {
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
/**
* 获取
* @return address
*/
public String getAddress() {
return address;
}
/**
* 设置
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + ", address = " + address + "}";
}
}
public class readi {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("..\\IOstream\\writei"));
ArrayList<Student> slist = (ArrayList<Student>)ois.readObject();
for (Student s :
slist) {
System.out.println(s);
}
ois.close();
}
}
public class writei {
public static void main(String[] args) throws IOException {
Student s1 = new Student("x",18,"nanjing");
Student s2 = new Student("y",19,"xianggan");
Student s3 = new Student("z",20,"shantou");
ArrayList<Student> slist = new ArrayList<>();
slist.add(s1);
slist.add(s2);
slist.add(s3);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("..\\IOstream\\writei"));
oos.writeObject(slist);
oos.close();
}
}