对象序列化
步骤:
-创建一个类,继承Serializable接口
-创建对象 -将对象写入文件
-从文件读取对象信息
1.创建一个类实现Serializable接口给
import java.io.Serializable;
/**
* @ClassName Goods
* @Description TODO
* @Author Ambition
* @Date 2021/1/20 17:25
* @Version 1.0.0
**/
public class Goods implements Serializable {
private String goodsId;
private String goodsName;
private double price;
public Goods(String goodsId, String goodsName, double price) {
this.goodsId = goodsId;
this.goodsName = goodsName;
this.price = price;
}
public Goods() {
}
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;
}
@Override
public String toString() {
return "商品信息 [编号:" + goodsId + ", 名称:" + goodsName
+ ", 价格:" + price + "]";
}
}
2.将对象写入文件
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* @ClassName GoodsTest
* @Description TODO 读取对象操作
* @Author Ambition
* @Date 2021/1/20 17:28
* @Version 1.0.0
**/
public class GoodsTest {
public static void main(String[] args) {
// 定义一个Goods类的对象
Goods goods1 = new Goods("gd001", "电脑", 3000);
try {
// 转换成文件流
FileOutputStream fos = new FileOutputStream("good.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(goods1);
// 清空缓存
oos.flush();
// 关闭流
fos.close();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.从文件读取对象信息
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* @ClassName GoodsTest2
* @Description TODO
* @Author Ambition
* @Date 2021/1/20 17:34
* @Version 1.0.0
**/
public class GoodsTest2 {
public static void main(String[] args) {
try {
//创建文件输入流
FileInputStream fis = new FileInputStream("good.txt");
// 用这个来连接文件输入流
ObjectInputStream ois = new ObjectInputStream(fis);
//读对象信息
Goods goods = (Goods) ois.readObject();
System.out.println(goods);
fis.close();
ois.close();
} catch (FileNotFoundException | ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
评论区