package com.java.io;
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;
import java.util.Iterator;
import java.util.List;
public class ObjectStream {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
outToFile(); //调用写方法
inFromFile(); //调用读方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void outToFile() throws Exception{ //对象写入到文件中
ObjectOutputStream obout = new ObjectOutputStream(new FileOutputStream("D:/文档/test.txt")); //创建对象输出流,并且用文件输出流实例化对象
Person p = new Person("张志强",27,"软件测试工程师");
Person p1 = new Person("王静",19,"销售经理");
Person p2 = new Person("李牧",23,"数据库管理员");
obout.writeObject(p); //保存对象到文件
obout.writeObject(p1); //保存对象到文件
obout.writeObject(p2); //保存对象到文件
obout.writeObject(null); //增加一个空对象,用于以后读取时的判断
obout.flush(); //强制刷下流;
obout.close(); //关闭流
}
public static void inFromFile() throws Exception{//从文件中读取对象
ObjectInputStream obin = new ObjectInputStream(new FileInputStream("D:/文档/test.txt"));//创建对象输入流,并且用文件输入流实例化对象
// Person p=null;
// p =(Person)obin.readObject(); //读取对象,
// System.out.println(p.getName()+"\t"+p.getAge()+"\t"+p.getJob());
Object obj=null;
while((obj =(Person)obin.readObject())!=null){ // 如果读到的对象为空则退出循环
Person per =(Person)obj; //读取对象,
System.out.println(per.getName()+"\t"+per.getAge()+"\t"+per.getJob());
};
obin.close();
}
}
//声明一个类,用于存储,读取
class Person implements Serializable{
private String name;
private int age;
private String job;
public Person(){}
public Person(String name, int age, String job) {
super();
this.setName(name);
this.setAge(age);
this.setJob(job);
}
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;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}