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分.... 我当时纠结迷茫该学啥以及我未来的路在哪里,和家人...