ObjectOutputStream可以将一个内存中的Java对象通过序列化的方式写入到磁盘的文件中。被序列化的对象必须要实现Serialzable序列化接口,否则会抛出异常。
创建对象
public class Users implements Serializable {private int userid;private String username;private String userage;public Users(int userid, String username, String userage){this.userid = userid;this.username = username;this.userage = userage;}public Users(){}public int getUserid(){return userid;}public void setUserid(int userid){this.userid = userid;}public String getUsername(){return username;}public void setUsername(String username){this.username = username;}public String getUserage(){return userage;}public void setUserage(String userage){this.userage = userage;}@Overridepublic String toString(){return "Users{" + "userid=" + userid + ", username='" + username + '\'' + ", userage='" + userage + '\'' +'}';}
}
序列化对象
public class TestObjectOutputStream {public static void main(String[] args){//创建对象输出字节流与文件输出字节流对象try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/data3"))){//创建Users对象Users users = new Users(1,"oldli","18");//将对象序列化到文件中oos.writeObject(users);//刷新oos.flush();}catch(IOException e){e.printStackTrace();}}
}