我們有時候想把一個對象寫到一個文件上,實現持久化,可以這么做
class User{ String userName ; String password; public User(String userName , String passwrod) { this.userName = userName; this.password = passwrod; } @Override public String toString() { return "用戶名:"+this.userName+ " 密碼:"+ this.password; } } public class Test { public static void main(String[] args) throws IOException, Exception { writeObj(); } //定義方法把對象的信息寫到硬盤上------>對象的序列化。 public static void writeObj() throws IOException{ //把user對象的信息持久化存儲。 User user = new User("admin","123"); //找到目標文件 File file = new File("/Users/chen/Downloads/obj.txt"); //建立數據輸出流對象 FileOutputStream fileOutputStream = new FileOutputStream(file); //建立對象的輸出流對象 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); //把對象寫出 objectOutputStream.writeObject(user); //關閉資源 objectOutputStream.close(); } }
運行時發現報錯java
Exception in thread "main" java.io.NotSerializableException: User
要求必要需實現serializable接口,serializable接口沒有任何方法,是一個標識接口。
在user類后面implements Serializable,然后打開obj.txt文件會發現是一堆字節碼文件,這是原先的對象編譯后的,我們如果要看這個對象需要反序列化

class User implements Serializable{ String userName ; String password; public User(String userName , String passwrod) { this.userName = userName; this.password = passwrod; } @Override public String toString() { return "用戶名:"+this.userName+ " 密碼:"+ this.password; } } public class Test { public static void main(String[] args) throws IOException, Exception { writeObj(); readObj(); } //定義方法把對象的信息寫到硬盤上------>對象的序列化。 public static void writeObj() throws IOException{ //把user對象的信息持久化存儲。 User user = new User("admin","123"); //找到目標文件 File file = new File("/Users/chen/Downloads/obj.txt"); //建立數據輸出流對象 FileOutputStream fileOutputStream = new FileOutputStream(file); //建立對象的輸出流對象 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); //把對象寫出 objectOutputStream.writeObject(user); //關閉資源 objectOutputStream.close(); } //把文件中的對象信息讀取出來-------->對象的反序列化 public static void readObj() throws IOException, ClassNotFoundException{ //找到目標文件 File file = new File("/Users/chen/Downloads/obj.txt"); //建立數據的輸入通道 FileInputStream fileInputStream = new FileInputStream(file); //建立對象的輸入流對象 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); //讀取對象信息 User user = (User) objectInputStream.readObject(); //創建對象肯定要依賴對象所屬 的class文件。 System.out.println("對象的信息:"+ user); } }
輸出:
對象的信息:用戶名:admin 密碼:123