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;
}
}
对象的二进制输入/输出
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 转换流 输入字节流的转换流:InputStreamReader 是字节流通向字符流的桥InputStreamRea...
- 图片的名称必须叫Default-568.png。(注:图片名称:Default-568格式为png) 必须把图片放...
- 2011年的夏天我收到我高考成绩单---赤裸裸的200分.... 我当时纠结迷茫该学啥以及我未来的路在哪里,和家人...