当前位置: 代码迷 >> J2SE >> 大家帮忙看看这个对象序列化的有关问题 十分感谢!
  详细解决方案

大家帮忙看看这个对象序列化的有关问题 十分感谢!

热度:235   发布时间:2016-04-24 01:27:19.0
大家帮忙看看这个对象序列化的问题 十分感谢!!
//我将对象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();
}


}


------解决方案--------------------
序列号类定义时:ObjectOutputStreamTest implements Serializable
------解决方案--------------------
Java code
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;    }    }
  相关解决方案