A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

对象序列化

对象的寿命通常随着创建该对象程序的终止而终止。有时可能需要将对象的状态保存下来,在需要时再将其恢复。对象状态的保存和恢复可以通过对象I/O流实现。

ObjectInputStream和ObjectOutputStream类的使用

向ObjectInputStream中读出对象

向ObjectOutputStream中写入对象

定义一个Student类,然后编写程序使用对象输出流将几个Student对象写入student.ser文件中,使用对象输入流读出对象。

实现对象的序列化和反序列化


package lx2;
import java.io.*;
public class Student implements Serializable {
        int id;
        String name;
        int age;
        String department;
        public Student(int id,String name,int age,String department) {
                this.id=id;
                this.name=name;
                this.age=age;
                this.department=department;
        }

}
package lx2;
import java.io.*;
import java.nio.file.*;
public class ObjectSerializeDemo {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                Path path= Paths.get("D:\\study\\data.ser");
                Student stu =new Student(16051001,"feafds",20,"ddsfaasaf");
                Student stu2 =new Student(16051002,"fefdes",20,"defdswhth");
                //序列化
                try(OutputStream output = Files.newOutputStream(path, StandardOpenOption.CREATE);
                                ObjectOutputStream oos= new ObjectOutputStream(output)){
                        oos.writeObject(stu);
                        oos.writeObject(stu2);                       
                }catch(IOException e) {
                        e.printStackTrace();
                }
                //反序列化
               
                try(InputStream input = Files.newInputStream(path, StandardOpenOption.READ);
                                ObjectInputStream ois =new ObjectInputStream(input)
                                ){
                        while(true) {
                                try {
                                Student stud =(Student)ois.readObject();
                                System.out.println("ID:"+ stud.id);
                                System.out.println("Name:"+ stud.name);
                                System.out.println("Age:"+ stud.age);
                                System.out.println("Dept:"+ stud.department);
                        }catch(EOFException e) {
                                break;
                        }
                }
                }catch(ClassNotFoundException | IOException e) {
                        e.printStackTrace();
                }

        }

}

---------------------
【转载】
作者:江南233244
原文:https://blog.csdn.net/qq_3913124 ... 609?utm_source=copy


3 个回复

倒序浏览
奈斯
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马