ObjectInputStream.readObject() 每次只讀取**一個**對象,需循環讀取直到流結束。
List dogs = new ArrayList<>();
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("/mnt/sdcard/somelocation/save.data"))) {
while (true) {
try {
Dog dog = (Dog) in.readObject();
dogs.add(dog);
} catch (EOFException e) {
break; // 讀取結束
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
EOFException 表示流結束,正常退出循環。out.writeObject(dog1); out.writeObject(dog2); ...Serializable,**建議顯式聲明 serialVersionUID** 防止版本不兼容。