I try to read data from file "sinhvien.dat" then push into array of Student.
My code:
private Student[] docFile() {
Student[] std = null;
FileInputStream f = null;
ObjectInputStream inStream = null;
try {
f = new FileInputStream("student.dat");
inStream = new ObjectInputStream(f);
std = (Student[]) inStream.readObject();// this line throw error
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
} catch (IOException e) {
System.out.println("Error Read file");
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException ex) {
}
}
if (f != null) {
try {
f.close();
} catch (IOException ex) {
}
}
}
return std;
}
Class Student
public class Student implements Serializable { private String studName; Student(String name) { this.studName = name; } public Student() { } public String getStudName() { return studName; } public void setStudName(String studName) { this.studName = studName; } @Override public String toString() { return "Student Name :" + studName; } }
I don't know how to fix this error. sorry for bad english :(
Student[], or at least not as its first object. How did you create that file?ClassCastException? What did you write to the file? Also note that you do not need to callcloseon each nested stream, it is the contract ofclosethat it does this. If you are using Java 7, consider using a try-with-resources block.