Java序列化简单的例子

来源:互联网 发布:追风软件怎么用 编辑:程序博客网 时间:2024/06/07 00:17
<span style="color:#FF0000;">Seerializable接口没有任何方法,所以实现仍然为空。,他被称为标记接口</span>package 序列化;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class ObjectSerializationApp {public static void main(String[] args) {// TODO Auto-generated method stubObjectOutputStream objectWriter = null;ObjectInputStream objectReader = null;try {objectWriter = new ObjectOutputStream(new FileOutputStream("student.dat"));objectWriter.writeObject(new Student(1, "John", "Mayor"));objectWriter.writeObject(new Student(2, "Sam", "Abel"));objectWriter.writeObject(new Student(3, "Anita", "Motwani"));System.out.println("打印出存在学生数据库中的列表");objectReader = new ObjectInputStream(new FileInputStream("student.dat"));for (int i = 0; i < 3; i++) {//方法readObject()返回一个Student对象,这个Student对象也通过调用隐式重写的toString()方法被打印到控制台System.out.println(objectReader.readObject());}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {try {objectWriter.close();objectReader.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}}// 学生类class Student implements Serializable {private String firstName;private String lastName;private int id;public Student(int id, String firstName, String lastName) {// TODO Auto-generated constructor stubthis.id = id;this.firstName = firstName;this.lastName = lastName;}// 重写toString()方法public String toString() {return ("ID:" + id + " " + firstName + " " + lastName);}}

0 0
原创粉丝点击