Java - Read all object use ObjectInputStream

when we use the ObjectInputStream to store a lot of objects in a file, and the problem is how to use methodreadObject() get all the objects from this file, since there are no readall() method provide by ObjectInputStream. Below code can help;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
ObjectIntputStream ois = new ObjectInputStream("/test.txt");
ArrayList<Student> al = new ArrayList<>();
try{
  while(true){
    Student s = (Student) ois.readObject(); 
    al.add(s);
  }
}catch(EOFException e){
  e.printStackTrace();
}
for(Student s : al){
  System.out.println(s.getName()+"," + s.getAge())
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
© 2020 Lingyun Yang
Built with Hugo
Theme Stack designed by Jimmy