package ten;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author mz
* 学习ObjectOutputStream类和ObjectInputStream类
*
*/
public class ObjectIODemo {
public static void main(String[] args) {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("luling"));
//建三个对象
BeautifulPerson one = new BeautifulPerson("Zhang Jingran", 18);
BeautifulPerson two = new BeautifulPerson("Zhang Yiran", 17);
BeautifulPerson three = new BeautifulPerson("Mu Haidong", 27);
//将三个对象写入文件
out.writeObject(one);
out.writeObject(two);
out.writeObject(three);
//关闭流和文件的连接
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("luling"));
BeautifulPerson readOne = (BeautifulPerson) in.readObject();
BeautifulPerson readTwo = (BeautifulPerson) in.readObject();
BeautifulPerson readThree = (BeautifulPerson) in.readObject();
System.out.println(readOne);
System.out.println(readTwo);
System.out.println(readThree);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class BeautifulPerson implements Serializable {
private String name;
private int age;
public BeautifulPerson() {
name = null;
age = 0;
}
public BeautifulPerson(String name, int age) {
this.name = name;
this.age = age;
}
//为了输出Person类,一定要有一个toString方法。
public String toString() {
return "name: " + name + ", " + "age: " + age;
}
}
网友评论