.dat文件通常存儲Java對象序列化數據。讀取並存入Vector(或ArrayList)的標準流程:
Vector<Student> studentVector = new Vector<>();
try (FileInputStream fis = new FileInputStream("stu.dat");
ObjectInputStream ois = new ObjectInputStream(fis)) {
while (true) {
try {
Student stu = (Student) ois.readObject();
studentVector.add(stu);
} catch (EOFException e) {
break; // 讀取完畢
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 現在 studentVector 包含所有學生對象
for (Student s : studentVector) {
System.out.println(s.getName() + " " + s.getId());
}
try-with-resources 自動關閉流(Java 7+)。EOFException 作為循環結束標誌,因為 readObject() 讀到文件末尾會拋出該異常。Student 類實現了 Serializable 接口,且 serialVersionUID 與寫入時一致。ArrayList 並自行控制同步。參考教程:Java對象序列化與反序列化詳解