读书人

对象序列化及反序列化步骤

发布时间: 2013-03-16 11:51:46 作者: rapoo

对象序列化及反序列化方法

/* *2013/3/13 星期三 8:13:33 *对象序列化及反序列化方法 */import java.io.*;public class TestObjectOutputStream {public static void main(String[] args) throws Exception {//实例化Student对象Student stu = new Student("小李",21,"男","zheshimima");//实例化ObjectOutputStream流对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:/Test/Test.txt"));//调用writeObject()方法将stu对象序列化oos.writeObject(stu);//关闭流对象oos.close();System.out.println("操作完毕");//实例化ObjectInputStream对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:/Test/Test.txt"));//将反序列化输出强制转换为Student类型Student newstu = (Student)ois.readObject();//输出对象nameSystem.out.println(newstu.getName());//输出结果为null,因为使用了transient进行了修饰,使敏感信息不被写入到数据流中System.out.println(newstu.getPassword());//关闭流ois.close();}}/* *定义一个Student类,实现Serializable接口,以便被序列化 */class Student implements Serializable{private String name;private String sex;private int age;private transient String password;public Student(String name,int age,String sex,String password){this.name = name;this.age = age;this.sex = sex;this.password = password;}public String getName() {return name;}public String getPassword() {return password;}}

读书人网 >编程

热点推荐