文档地址 http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
序列化 : 把java对象转换成字节序列的过程
反序列化: 把字节序列恢复为java对象的过程
第一步 新建一个类实现 Serializable 接口 重写toString 方法
public class Goods implements Serializable{
private String goodsId;
private String goodsName;
private double price;
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Goods(String goodsId, String goodsName, double price) {
super();
this.goodsId = goodsId;
this.goodsName = goodsName;
this.price = price;
}
@Override
public String toString() {
return " [商品编号=" + goodsId + ", 商品名称=" + goodsName + ", 商品价格=" + price + "]";
}
}
第二步 测试 方法
void Test(){
Goods goods =new Goods("gs001", "电脑", 30004);
try {
FileOutputStream fos = new FileOutputStream("/users/yifei/desktop/assets/reader.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(goods);//将goods用ObjectOutputSteam流写入xxx.txt中 ,进行持久化操作
os.writeBoolean(true);//也可以写入其他类型
os.flush();//当对象过短时会存在缓冲区中不会自动写入, 需要手动写入
FileInputStream fis = new FileInputStream("/users/yifei/desktop/assets/reader.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Goods g1=(Goods)ois.readObject();//将 goods对象从 xxx.txt 用 ObjectInputStream中读出
boolean b =ois.readBoolean();/写入的对象都可以读出
System.out.println(g1);
System.out.println(b);
fis.close();
ois.close();
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(EOFException e) { //文档已经读到末尾的异常
System.out.println(e);
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}catch ( ClassNotFoundException e) {
e.printStackTrace();
}
}