java序列化写入多个对象_Java序列化读写多个对象的方法

Person类用来序列化public class Person implements Serializable{

private String name;

private int age;

public Person(String name, int age) {

super();

this.name = name;

this.age = age;

}

}

方法一:存入文件时,将几个对象放入一个Object[] 数组中,然后再读取。private static void read() throws ClassNotFoundException, IOException {

//创建序列化流对象

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Object.txt"));

//读出

Object[] objArr =(Object[])ois.readObject();

for(Object obj : objArr) {

System.out.println(obj);

}

ois.close();

}

private static void write() throws IOException {

//创建序列化流对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Object.txt"));

//创建对象

Person[] p = {new Person("Mike",22), new Person("Like",44)};

//存入

oos.writeObject(p);

oos.close();

}

方法二:一个一个放入,需要写完对象后加入null作为结束标志private static void read() throws ClassNotFoundException, IOException {

//创建序列化流对象

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Object.txt"));

Object obj =null;

while((obj=ois.readObject())!=null) {

System.out.println(obj);

}

ois.close();

}

private static void write() throws IOException {

//创建序列化流对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Object.txt"));

//创建对象

Person p1 = new Person("Mike",22);

Person p2 = new Person("Like",44);

//存入

oos.writeObject(p1);

oos.writeObject(p2);

oos.writeObject(null);//加入null 用来判断是否到末尾,如果不加会报错EOFException

oos.close();

}

方法三:用available判断是否达到了文件末尾private static void read() throws ClassNotFoundException, IOException {

//创建序列化流对象

FileInputStream fis = new FileInputStream("Object.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

//读取

Object obj =null;

while(fis.available()>0) {

obj=ois.readObject();

System.out.println(obj);

}

ois.close();

}

private static void write() throws IOException {

//创建序列化流对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Object.txt"));

//创建对象

Person p1 = new Person("Mike",22);

Person p2 = new Person("Like",44);

//存入

oos.writeObject(p1);

oos.writeObject(p2);

oos.close();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值