关于Java在反序列化流时抛出java.io.EOFException异常处理方法

刚开始在反序列化流的时候,抛出了EOFException异常;

处理办法:

自定义类中有没有实现Serializable接口;

在反序列化流的时候需要将ovbject强转自定义类

Student obj = (Student) ois.readObject();






import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;


public class Test {


public static void main(String[] args) throws  Exception {
File f = new File("sava.txt");



if(f.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));

Student obj = (Student) ois.readObject();
System.out.println( obj);


ois.close();
}else{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
Scanner sc = new Scanner(System.in);
Student s = new Student();
System.out.println("请输入学生姓名");
    s.setName(sc.next());
System.out.println("请输入学生学号");
    s.setId(sc.nextInt());
System.out.println("请输入学生身份证号");
s.setIdcardnum(sc.nextInt());
System.out.println("请输入学生的数学成绩");
s.setMathcj(sc.nextDouble());
System.out.println("请输入学生的Java成绩");
s.setJavacj(sc.nextDouble());
System.out.println("请输入学生的英语成绩");
s.setEnglishcj(sc.nextDouble());
oos.writeObject(s);
oos.close();
}



}

}




public class Student implements Serializable {
/**

*/
private static final long serialVersionUID = -8763490558256462498L;
private int id;
private String name;
transient private int idcardnum;
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", javacj=" + javacj + ", mathcj=" + mathcj + ", englishcj="
+ englishcj + "]";
}
public Student(int id, String name, int idcardnum, double javacj, double mathcj, double englishcj) {
super();
this.id = id;
this.name = name;
this.idcardnum = idcardnum;
this.javacj = javacj;
this.mathcj = mathcj;
this.englishcj = englishcj;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
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 int getIdcardnum() {
return idcardnum;
}
public void setIdcardnum(int idcardnum) {
this.idcardnum = idcardnum;
}
public double getJavacj() {
return javacj;
}
public void setJavacj(double javacj) {
this.javacj = javacj;
}
public double getMathcj() {
return mathcj;
}
public void setMathcj(double mathcj) {
this.mathcj = mathcj;
}
public double getEnglishcj() {
return englishcj;
}
public void setEnglishcj(double englishcj) {
this.englishcj = englishcj;
}
private double javacj;
private double mathcj;
private double englishcj;
}

你可能感兴趣的:(关于Java在反序列化流时抛出java.io.EOFException异常处理方法)