对象输入流

对象输入流写和读
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 + "]";
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值