JAVA中对象的存储和读取简析

首先创建一个File对象

File file = new File("D:/program/JAVA/src/start/data.txt");   //打开存储文件
        if(!file.exists()) {
            try{
                file.createNewFile();
                System.out.println("文件已创建");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

先介绍单个对象如何存储。上代码

向文件输入对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(DATA);
oos.close();

提取文件中的对象

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
customer DATA = (customer)ois.readObject();                                      //customer是一个自定义类
ois.close();

现在介绍如何存储一个对象的数组

向文件输入对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(DATA);
oos.close();

提取文件中的对象

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
customer DATA[] = (customer[])ois.readObject();                                 //可以看到只有部分改动 
ois.close();

如果想要向文件中已经存在的数组中追加新对象的话,可以新创建一个新的数组(可能是我比较呆,只能想到这一个方法:-) ),此数组的长度为原数组长度加1。代码如下:

customer WXH[] = new customer[DATA.length+1];
for(int i=0;i<DATA.length;i++){
    WXH[i] = new customer();
    WXH[i] = DATA[i];
}
WXH[DATA.length] = new customer();
WXH[DATA.length].setname();                                                      //这些为自定义类的方法,请忽略~
WXH[DATA.length].getkey();
WXH[DATA.length].savemoney();

//存档
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(WXH);
oos.close();

总结一下,对象的存储和读取的核心内容就是两种类的应用,只要多使用的话还是很容易掌握的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值