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);
//關(guān)閉流和文件的連接
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;
}
}
對象的二進制輸入/輸出
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 轉(zhuǎn)換流 輸入字節(jié)流的轉(zhuǎn)換流:InputStreamReader 是字節(jié)流通向字符流的橋InputStreamRea...
- 圖片的名稱必須叫Default-568.png。(注:圖片名稱:Default-568格式為png) 必須把圖片放...
- 清邁是泰國第二大城市,是清邁府的首府,也是泰國北部政治、經(jīng)濟、文化的中心,其發(fā)達程度僅次于首都曼谷。市內(nèi)風景秀麗,...
- 2011年的夏天我收到我高考成績單---赤裸裸的200分.... 我當時糾結(jié)迷茫該學啥以及我未來的路在哪里,和家人...