1.首先,对即将要操作的java对象的类需要实现序列化接口Serializable,代码如下:
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String name = null;
private String pwd = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User [name=" + name + ", pwd=" + pwd + "]";
}
}
2.将user类序列化存储到文件中,并从文件中反序列化读取java类,代码如下:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializedUser {
public static void main(String[] args) throws Exception {
User user = new User();
user.setName(“zgj”);
user.setPwd(“zgjzzm”);
System.out.println(user.toString());
//将user对象序列化存储到文件
ObjectOutputStream ots = new ObjectOutputStream(new FileOutputStream(“C:\Users\Administrator\Desktop\编程学习\user.xml”));
ots.writeObject(user);
ots.flush();
ots.close();
//从文件中反序列化读取user对象信息
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“C:\Users\Administrator\Desktop\user.xml”));
User user2 = (User)in.readObject();
System.out.println(user2.toString());
}
}
注意:文件类型可以使xml,也可以是txt
运行结果: