//我将对象student序列化到hello.txt文件为什么 反序列化后student的name和age都成0了啊??import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class ObjectOutputStreamTest  {
    
public static void main(String[] args) throws FileNotFoundException, IOException {
 
ObjectOutputStream oos=new ObjectOutputStream(new  FileOutputStream("D:\\test\\hello.txt"));
 
Student s=new Student("安安",20);

oos.writeObject(s);
    oos.close();
}

}
//反序列化
public static void main(String[] args) {
 
try {
//实例化对象输入流
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\test\\hello.txt"));

try {
//反序列化对象
Student stu=(Student) ois.readObject();

System.out.println("学生姓名"+stu.getName());
System.out.println("学生年龄"+stu.getAge());


} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

解决方案 »

  1.   

    序列号类定义时:ObjectOutputStreamTest implements Serializable 
      

  2.   

    是:Student implements Serializable  
      

  3.   

    public class Student implements Serializable{ private String name;
    private int age;

    public Student() {

    }

    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
      

  4.   


    public class ObjectOutputStreamTest { public static void main(String[] args) throws FileNotFoundException,
    IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
    "hello.txt")); Student s = new Student("安安", 20); oos.writeObject(s);
    oos.flush();
    oos.close(); // 反序列化 try {
    // 实例化对象输入流
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
    "hello.txt")); try {
    // 反序列化对象
    Student stu = (Student) ois.readObject(); System.out.println("学生姓名:" + stu.getName());
    System.out.println("学生年龄:" + stu.getAge()); } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    } catch (FileNotFoundException e){
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace(); } }}
    class Student implements Serializable{

    private String name;
    private int age; public Student(String name,int age) {
    this.name = name;
    this.age = age;
    } public int getAge() {
    return age;
    } public void setAge(int age) {
    this.age = age;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }

    }
    代码没问题啊。
      

  5.   

    你反序列化后  能输出student的名字安安 和年龄20
      

  6.   

    我运行以后 姓名和年龄是null
      

  7.   

    我知道了  一不小心student的构造方法写错了 
      

  8.   

    那你打开文件看有没有东西,有东西,说明是取的时候出问题了呗。如果没有,说明存的时候出问题,
    不过我运行我自己写的,怎么一点问题都没有??你自己检查哪里错了
    我只是帮你加了点东西
    1.student的构造方法,我相信你也写了,不然会报错。
    2.oos.flush,清缓存。