1. 程式人生 > >ObjectInputStream與ObjectOutputStream使用以及與DataInputStream,DataOutput區別

ObjectInputStream與ObjectOutputStream使用以及與DataInputStream,DataOutput區別

ObjectInputStream與ObjectOutputStream使用以及與DataInputStream,DataOutput區別

結論

1.Object相當於裝IO流的一個盒子,我們可以把物件比作一個個拼好的積木,IO流就是拼積木的積木塊,那麼如果要搬走積木(物件),肯定需要把積木(物件)先拆了,再扔進盒子(Object)裡,這就是為什麼物件要序列化(Serializable)

2.當然裝的時候我們可以有兩種裝法一種是全放入(output.writeObject(this))第一種盒子(ObjectInputStream)另一種是分類別 (如:,比如屋頂,地板,這就是流裡面的) 放入(output.writeUTF(number),output.writeUTF(name),output.writeInt(age)…)

第二種盒子(DataInputStream),所以在搬到另一個地方的時候,第一種盒子裡我們把混在一起的積木塊倒出((Member)intput.readObject()),第二種盒子則是分塊拿出來({input.readUTF(),input.readUTF(),input.readInt()…)

#### 演示程式碼

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import
java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Test { public static void main(String[] args) throws IOException, ClassNotFoundException { Member[] mebers= {new Member("iotest/4.txt","xiaohua",1),new
Member("iotest/4.txt","xiaoming",3),new Member("iotest/4.txt","xiaofang",3)}; for(Member b:mebers) { b.save(); } System.out.println(Member.load("iotest/4.txt")); } } class Member implements Serializable { private String dest; private String name; private int age; /** * * @param dest 寫出的文目的地 * @param name使用者名稱 * @param age使用者年齡 */ public Member(String dest,String name, int age) { super(); this.dest=dest; this.name = name; this.age = age; } 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; } @Override public String toString() { // TODO Auto-generated method stub return String.format("%s %d", name,age); } public void save() throws FileNotFoundException, IOException { try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(dest))) { output.writeObject(this); } } /** * * @param number src 讀入的原始檔夾 * @return * @throws FileNotFoundException 檔案未發現異常 * @throws IOException io異常 * @throws ClassNotFoundException 檔案目錄異常 */ public static Member load(String number) throws FileNotFoundException, IOException, ClassNotFoundException { Member m;//接收讀入的物件 try (ObjectInputStream output = new ObjectInputStream(new FileInputStream(number))) { m=(Member)output.readObject(); } return m; } }