import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
transient private String password;
private int age;
public User(String name, String password, int age) {
super();
this.name = name;
this.password = password;
this.age = age;
}
public String toString() {
return "User [name=" + name + ", password=" + password + ", age=" + age + "]";
}
}
步骤1:先创建一个类用来转化,提供构造器和ToString方法,以便于反序列化回来之后打印显示。
步骤2:创建对象流对象,在对象流对象中包装基本字节流。
步骤3:调用对象流对象的writeObject /readObject方法。
步骤4: 关闭资源
package object;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectDemo {
public static void main(String[] args) throws Exception {
File f =new File("process/userInformation.txt");
writeObject(f);
readObject(f);
}
//对象反序列化
private static void readObject(File f) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object obj = ois.readObject();
System.out.println(obj);
ois.close();
}
//对象序列化
private static void writeObject(File f) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(new User("李白","123456",17));
oos.close();
}
}