main()
public static void main(String[] args) throws IOException {
ObjectInputStream oos = null;
Student student;
try {
oos = new ObjectInputStream(new FileInputStream("F:\\testout.txt"));
for(int i=0;i<4;i++)
{
student= (Student) oos.readObject();
System.out.println(student.getName());
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ObjectOutputStreamExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
oos.close();
}
Student.java
package file;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
private int age;
public void Studet() {}
public Student(int id, String name, String address, int age) {
super();
this.id = id;
this.name = name;
this.address = address;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student@[id=" + id + " , name=" + name + ", "
+ "address= " + address + ",age =" + age+ "]";
}
}
Mình đã sử dụng: oos = new ObjectOutputStream(new FileOutputStream("F:\\testout.txt",true)); để ghi tiếp dữ liệu kiểu Sinhvien vào file, nếu ghi 1 lúc 3 object kiểu Sinhvien trong 1 lần chạy chương trình thì có thể đọc cả 3 object đấy mà không lỗi , nhưng nếu ghi từng object 1 thì khi đọc 1 lúc nhiều Sv sẽ nhảy ra lỗi:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1599)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at file.ObjectOutputStreamExample.main(ObjectOutputStreamExample.java:25)
Cho em hỏi làm thế nào để đọc nhiều object mà không bị lỗi? (không muốn sử dụng ghi cả 1 mảng Sinhvien[] rồi đọc).
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?