对象序列化Serializable

序列化Serializableimport java.io.Serializable;/* * Student类,实体类 * 实现Serializable接口,表示可以被序列化 */{serialVersionUID = 3773074579371927286L;private String id;private String name;private String sex;age; height;public Student() {}public Student(String id, String name, String sex, int age, double height) {super();this.id = id;this.name = name;this.sex = sex;this.age = age;this.height = height;}public String getId() {return id;}(String id) {this.id = id;}public String getName() {return name;}(String name) {this.name = name;}public String getSex() {return sex;}(String sex) {this.sex = sex;}() {return age;}(int age) {this.age = age;}() {return height;}(double height) {this.height = height;}@Overridepublic String toString() {return “Student[id=” + id + “,name=” + name + “,sex=” + sex + “,age=”+ age + “]”;}}序列化和反序列化对象/* * ObjectOutputStream和ObjectInputStream类 * 分别用来序列化和反序列化对象 */public class Test02 {(String[] args) throws Exception {writeObject();readObject();}() throws IOException {Student stu1 = new Student(“s001”, “张三”, “男”, 20, 175.5);Student stu2 = new Student(“s002”, “李四”, “女”, 22, 170.5);List<Student> students=new ArrayList<Student>();students.add(stu1);students.add(stu2);//定义一个文件输出流FileOutputStream fos=new FileOutputStream(“D:\\Java\\students”);//添加缓冲BufferedOutputStream bos=new BufferedOutputStream(fos);//定义对象输出流ObjectOutputStream oos=new ObjectOutputStream(bos);//序列化对象/*oos.writeObject(stu1);oos.writeObject(stu2);*/oos.writeObject(students);oos.flush();System.out.println(“序列化对象成功!”);oos.close();}() throws Exception{FileInputStream fis=new FileInputStream(“D:\\Java\\students”);BufferedInputStream bis=new BufferedInputStream(fis);ObjectInputStream ois=new ObjectInputStream(bis);//反序列化/*Student stu1=(Student) ois.readObject();Student stu2=(Student)ois.readObject();System.out.println(stu1);System.out.println(stu2);*/List<Student> students=(List<Student>) ois.readObject();for(Student stu:students){System.out.println(stu);}}}

,什么天荒地老,什么至死不渝。都只是锦上添花的借口…

对象序列化Serializable

相关文章:

你感兴趣的文章:

标签云: