對象的輸入輸出流的作用: 用於寫入對象 的信息讀取對象的信息。 對象的持久化。 比如:用戶信息。
ObjectInputStream : 對象輸入流
ObjectOutPutStream :對象輸出流
對象輸入輸出出流的使用注意點:
1.如果想將一個對象寫入到磁盤中,那么對象所屬的類必須要進行序列化實現Serializable接口,Serializable接口沒有任何方法 ,是一個標記接口
2.如果對象所屬的類的成員變量發生改變,你在讀取原來的對象是就會報錯,如果想要解決報錯,保證serialVersionUID是唯一。
3.如果你不想將某些信息存入到磁盤 就可以同過transient關鍵字修飾成員變量
4.如果一個類中引用了另外的一個類,那么另外的這個類也要實現Serializable接口。
package com.beiwo.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Cat implements Serializable { private static final long serialVersionUID = 1L; // 保證所取對象信息唯一 String name; public Cat(String name) { // TODO 自動生成的構造函數存根 this.name = name; } @Override public String toString() { // TODO 自動生成的方法存根 return "cat.name" + this.name; } } class Person implements Serializable { private static final long serialVersionUID = 1L; // 保證所取信息唯一 String name; int age; int id; String sex; // 如果不想把某些信息存入磁盤中 ,則需要通過transient關鍵字修飾成員變量 transient String password; Cat cat; // 構造方法 public Person(String name, int age, int id, String password, Cat cat){ this.name = name; this.age = age; this.id = id; this.password = password; this.cat = cat; } } public class demo4 { /** * @param args * @throws IOException * @throws ClassNotFoundException */ public static void main(String[] args) throws IOException, ClassNotFoundException { // 調用方法 writeObject(); readObject(); } // 讀取數據到磁盤中 public static void readObject() throws IOException, ClassNotFoundException { // TODO 自動生成的方法存根 // 找到目標文件 File file = new File("C:\\Users\\cdlx2016\\Desktop\\2\\cc.txt"); // 建立通道 FileInputStream inputStream = new FileInputStream(file); // 創建對象輸入流 ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); // 讀取數據 Person person = (Person)objectInputStream.readObject(); // 打印數據 System.out.println("name: " + person.name + " age: " + person.age + " id: " + person.id + " 密碼:" + person.password + " cat: " + person.cat); // 關閉數據 objectInputStream.close(); } // 寫入對象 private static void writeObject() throws IOException { // 找到目標文件 File file = new File("C:\\Users\\cdlx2016\\Desktop\\2\\cc.txt"); // 建立通道 FileOutputStream fileOutputStream = new FileOutputStream(file); // 創建對象輸出流 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); // 創建對象 Person person = new Person("李四", 20, 1203, "369852", new Cat("大肥")); // 寫入數據 objectOutputStream.writeObject(person); // 關閉流 objectOutputStream.close(); } }