Java学习之对象流,序列化,反序列化--2015-03-02

来源:互联网 发布:linux修改内核参数 编辑:程序博客网 时间:2024/05/18 22:17

三、引用类型(对象) 保留数据+类型


反序列化: 输入流: ObjectInputStream readObject()
序列化:   输出流: ObjectOutputStream writeObject()
注意:
1)、先序列化后反序列化;反序列化顺序与序列化一致

2)、不是所有的对象都可以序列化, 必须实现 java.io.Serializable 接口

          不是所有的属性都需要序列化, transient


public class TestObjectStream {public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {write("E:/workspace/images/a.txt");read("E:/workspace/images/a.txt");}// 反序列化public static void read(String src) throws FileNotFoundException,IOException, ClassNotFoundException {File file = new File(src);ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));Object obj = is.readObject();if (obj instanceof Student) {Student stu = (Student) obj;System.out.println(stu.getName());System.out.println(stu.getNo());}}// 序列化public static void write(String destpath) throws FileNotFoundException,IOException {Student stu = new Student("世界", 10);File file = new File(destpath);ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));os.writeObject(stu);os.close();}}class Student implements java.io.Serializable {private String name; // 可序列化private transient int no;// 不序列化public Student() {}public Student(String name, int no) {super();this.name = name;this.no = no;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}}


0 0
原创粉丝点击