IO流——物件流(ObjectOutputStream&ObjectInputStream)
阿新 • • 發佈:2018-12-20
物件流
ObjectOutputStream
將物件持久化(永久儲存在磁碟上)
注意:要儲存的物件的類要實現序列化介面(serializable)
構造方法
protected ObjectOutputStream()throws IOException,SecurityException
public ObjectOutputStream(OutputStream out)throws IOException
Code:
持久化ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("對");
arrayList.add("象");
arrayList.add("流");
arrayList.add("測");
arrayList.add("試");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/w.txt"));
//將arrayList持久化
oos.writeObject(arrayList);
持久化自定義類的物件:
/**
* @author maple
*持久化Student, 要實現Serializable介面
*/
public class Student implements Serializable{
/**
* serialVersionUID: 這個值,是在兩端【不同的電腦 物件傳遞之後,比較型別的一個依據】
* 1.本電腦建立了一個學生物件
* 2.當我們把這個物件傳遞到其他電腦的時候,這個物件,要與其他電腦裡面的Student類比較型別 是否一致
* 3.除了判斷型別,還會判斷serialVersionUID
*/
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
//自己新建一個測試類,將主方法拷貝過去
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Student stu1 = new Student("小米",4);
Student stu2 = new Student("蘋果",6);
//進行持久化
/*ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/x.txt"));
oos.writeObject(stu1);
oos.writeObject(stu2);
//這裡在最後放入null是為了標誌已經到末尾了
oos.writeObject(null);*/
}
ObjectInputStream
將持久化的物件拿出來
構造方法
protected ObjectInputStream()throws IOException,SecurityException
public ObjectInputStream(InputStream in)throws IOException
//讀取上面持久化的arrayList
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/w.txt"));
Object readObject = ois.readObject();
System.out.println(readObject);
讀取上面自定義Student類的物件
//將持久化的資料拿出來
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/x.txt"));
/*Object object1 = ois.readObject();
Object object2 = ois.readObject();
System.out.println(object1);
System.out.println(object2);*/
Object obj = null;
while ((obj = ois.readObject()) != null) {
System.out.println(obj);
}