当我将内容从文件强制转换到对象时,java抛出java.lang.ClassCastException

当我将内容从文件强制转换到对象时,java抛出java.lang.ClassCastException,java,Java,我尝试从文件“sinhvien.dat”中读取数据,然后将其放入学生数组中 我的代码: private Student[] docFile() { Student[] std = null; FileInputStream f = null; ObjectInputStream inStream = null; try { f = new FileInputStream("student.dat"); inStream = new

我尝试从文件“sinhvien.dat”中读取数据,然后将其放入学生数组中

我的代码:

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;
}
班级学生

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; } }
我不知道如何修正这个错误。 对不起,英语不好:(

这意味着您不能将单个学生对象强制转换为学生对象数组。 我认为您序列化了一个
学生
,并尝试反序列化一个
学生[]
。前缀
[L
表示一个数组


看看您的序列化程序。

好吧,看起来该文件没有序列化的
Student[]<或代码>,或至少不是它的第一个对象。您是如何创建该文件的?什么是代码> CLSASTASTROVSUTS/CODE >?您对文件写了什么?也请注意,在每个嵌套流中不需要调用<代码>关闭<代码>,它是“代码>关闭< /代码>的契约,它是这样做的。如果您使用java 7,请考虑使用一个尝试WI。th resources block.thread“thread-3”java.lang.ClassCastException中的异常:btvn_l5.Student不能强制转换为[Lbtvn_l5.Student;@user3079521从不在注释中发布代码。这不是建设性的-您可以看到它难以辨认。您可以编辑您的答案。
Exception in thread "Thread-3" java.lang.ClassCastException: btvn_l5.Student cannot be cast to [Lbtvn_l5.Student;