序列化object
创建一个对象,这个对象需要implements Serializable
public class Products implements Serializable
{
public String pId;
public String pName;
public float pPrice;
public Products(String pId, String pName, float pPrice)
{
this.pId = pId;
this.pName = pName;
this.pPrice = pPrice;
}
public String toString()
{
return this.pId+";"+this.pName+";"+this.pPrice;
}
}
实现序列化和反序列化
public class Demo
{
public static void main(String[] args) throws Exception
{
Products p1 = new Products("p01", "香蕉", 10.8f);
Products p2 = new Products("p02", "苹果", 10.8f);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/test/pdt.obj"));
oos.writeObject(p1);
oos.writeObject(p2);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/test/pdt.obj"));
Products p5 = (Products) ois.readObject(); //一次读取一个object,按从前到后的顺序读取
Products p6 = (Products) ois.readObject();
ois.close()
System.out.println(p5);
System.out.println(p6);
}
}
列表的序列化和反序列化
//列表中的object需要实现Serializable接口
public class Demo
{
public static void main(String[] args) throws Exception
{
Products p1 = new Products("p01", "香蕉", 10.8f);
Products p2 = new Products("p02", "苹果", 10.8f);
ArrayList<Products> list = new ArrayList<Products>();
list.add(p1);
list.add(p2);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/test/list.obj"));
oos.writeObject(list);
oos.close();
System.out.println(list);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/test/list.obj"));
ArrayList<Products> list1 = (ArrayList<Products>) ois.readObject();
System.out.println(list1);
ois.close();
}
}