0

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 :(

4
  • 4
    Well, looks like that file doesn't have a serialized Student[], or at least not as its first object. How did you create that file? Commented Dec 8, 2013 at 9:46
  • 1
    What exactly is the ClassCastException? What did you write to the file? Also note that you do not need to call close on each nested stream, it is the contract of close that it does this. If you are using Java 7, consider using a try-with-resources block. Commented Dec 8, 2013 at 9:51
  • Exception in thread "Thread-3" java.lang.ClassCastException: btvn_l5.Student cannot be cast to [Lbtvn_l5.Student; Commented Dec 8, 2013 at 10:58
  • @user3079521 Never post code in comments. This is not constructive - you can see yourself that it is illegible. You can edit your answer. Commented Dec 8, 2013 at 14:37

1 Answer 1

2
Exception in thread "Thread-3" java.lang.ClassCastException: btvn_l5.Student cannot be cast to [Lbtvn_l5.Student;

This means, that you cannot cast a single Student-obect into an array of Student-objects. I think you serialize a Student and try to deserialize a Student[]. Th prefix [L indicates an array.

Take a look at you serializer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.