对象输入流写和读
package Text0425;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
/*
* 对象输入流
* 将对象整合到集合中,在写入文件中
* 对象类 必须实现Serializable的接口,对对象进行反码标记
* 读文件时,需要将集合中的对象进行向下转型--强转
*
*/
public class ObjectText {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\object.txt"));
Person p1 = new Person("zhangsan", 30);
Person p2 = new Person("lisi", 28);
Person p3 = new Person("wangwu", 35);
//
Student s1 = new Student("xiaofang", 20);
Student s2 = new Student("xiaocai", 600000);
Student s3 = new Student("xiaoye", 1);
ArrayList aList = new ArrayList();// 将对象整合到数组中
aList.add(p1);
aList.add(p2);
aList.add(p3);
aList.add(s1);
aList.add(s2);
aList.add(s3);
oos.writeObject(aList);// 将集合写进文件中
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\object.txt"));
ArrayList l = new ArrayList();// 创建集合接收读的信息
l = (ArrayList) ois.readObject();// 将object类型,向下转型成为集合类型,并且接收
for (Object object : l) {
if (object instanceof Person) {// 判断集合中的元素是否是Person的类型,并且向下转型
Person pp = (Person) object;
System.out.println(pp.toString());
} else if (object instanceof Student) {// 判断集合中的元素是否是Student的类型,并且向下转型
Student ss = (Student) object;
System.out.println(ss.toString());
}
}
ois.close();
}
}
class Person implements Serializable {// 对类的对象进行反序列
private String name;
private int age;
public Person(String name, int age) {
super();
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 "person [name=" + name + ", age=" + age + "]";
}
}
class Student implements Serializable {
private String name;
private int id;
public Student(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return id;
}
public void setAge(int age) {
this.id = age;
}
@Override
public String toString() {
return "person [name=" + name + ", age=" + id + "]";
}
}