要实现对象的序列化,最直接的操作就是实现Serializable接口,使用IO流中的对象流可以实现序列化操作,将对象保存到文件,再读取出来。
首先创建一个对象,并实现Serializable接口:import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
用对象流写一个保存对象与读取对象的工具类:import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
// 保存对象,序列化
public static void saveObject(Object object) throws Exception {
ObjectOutputStream out = null;
FileOutputStream fout = null;
try {
fout = new FileOutputStream("D:/user.txt");
out = new ObjectOutputStream(fout);
out.writeObject(object);
} finally {
fout.close();
out.close();
}
}
// 读取对象,反序列化
public static Object readObject() throws Exception {
ObjectInputStream in = null;
FileInputStream fin = null;
try {
fin = new FileInputStream("D:/user.txt");
in = new ObjectInputStream(fin);
Object object = in.readObject();
return object;
} finally {
fin.close();
in.close();
}
}
}
测试:public class Main {
public static void main(String[] args) {
User user = new User();
user.setName("海绵宝宝");
user.setAge(20);
// 保存
try {
SerializeUtil.saveObject(user);
} catch (Exception e) {
System.out.println("保存时异常:" + e.getMessage());
}
// 读取
User userObject;
try {
userObject = (User) SerializeUtil.readObject();
System.out.println(userObject);
} catch (Exception e) {
System.out.println("读取时异常:" + e.getMessage());
}
}
}
/*
* 运行结果:User [name=海绵宝宝, age=20]
*/