对象序列化:把Java对象写入到文件中去
package com.itheima.d3;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class Test1 {public static void main(String[] args) {try(//2、创建一个对象字节输出流包装原始的字节输出流ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("IO/src/itheima11.txt"));) {//1、创建一个Java对象User u = new User("rch", "任朝晖", 18, "rch041126");//3、序列化对象到文件中去oos.writeObject(u);System.out.println("序列化对象成功");} catch (Exception e) {e.printStackTrace();}}
}
注意:对象如果需要序列化,必须实现序列化接口
package com.itheima.d3;import java.io.Serializable;//注意:对象如果需要序列化,必须实现序列化接口
public class User implements Serializable {private String loginName;private String userName;private int age;//transient 这个成员变量不参与序列化 private transient String passWord;public User() {}public User(String loginName, String userName, int age, String passWord) {this.loginName = loginName;this.userName = userName;this.age = age;this.passWord = passWord;}public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getPassWord() {return passWord;}public void setPassWord(String passWord) {this.passWord = passWord;}@Overridepublic String toString() {return "User{" +"loginName='" + loginName + '\'' +", userName='" + userName + '\'' +", age=" + age +", passWord='" + passWord + '\'' +'}';}
}
对象饭序列化:把文件里的Java对象读取出来
package com.itheima.d3;import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;public class Test3 {public static void main(String[] args) {try(//1、创建一个对象字节输入流管道,包装 低级的字节输入流与源文件接通ObjectInputStream ois =new ObjectInputStream(new FileInputStream("IO/src/itheima11.txt"));) {User u = (User) ois.readObject();System.out.println(u);} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}
}