首页 > 技术文章 > 序列化和反序列化实例

-llf 2019-03-17 16:20 原文

public class User implements Serializable {


private static final long serialVersionUID = 5584689761718449673L;

private int id;
private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

public class SerializableText {

private static String filename = "D:/xunleihua.txt";

//序列化
public static void writeO(Serializable s){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(s);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//反序列化
public static Object readO(){
Object o = null;
try {
ObjectInput oi = new ObjectInputStream(new FileInputStream(filename));
o = oi.readObject();
oi.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return o;

}
}

//测试
   User u = new User();
u.setId(1);
u.setName("Lawrence");
// SerializableText.writeO(u);
// SerializableText.readO();

推荐阅读