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;
}
@Override
public 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();
}
}
}