Java 怎样将多个对象读取出来,怎样判断是否读完?

2025-06-22 12:02:46
推荐回答(1个)
回答1:

您好,提问者:
    将对象存入文件中?是用的序列化吧?

    如果确实报错,下面我写的一个例子,你可以看一下。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Demo {
    public static void main(String[] args) throws Exception{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\x.person"));
        oos.writeObject(new Person("张三",20));
        oos.writeObject(new Person("李四",18));
        oos.writeObject(new Person("王五",23));
        oos.writeObject(null);//插入null是用来判断是否读取到结尾。
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\x.person"));
        Object obj = null;
        while((obj= ois.readObject())!=null){ //如果为null就读取到文件结尾了。
            Person person = (Person)obj;
            System.out.println(person);
        }
    }
}
class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return this.name+":"+this.age;
    }
}