5.19序列化与反序列化

package org.westos.IO流中序列化与反序列化;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化:ObjectOutputStream
 * 反序列化:ObjectInputStream
 * 序列化是将对象按流的方式存储到文件中或者在网络中传输
 * 反序列化用于恢复那些以前序列化的对象
 * 对于那些想要被序列化的类需要实现(标记接口)Serlizable并且产生一个随机的版本号
 * 		防止出现NotSerlizableException和InvalidClassException
 * 序列化构造方法:
 * 		public ObjectOutputStream(OutputStream out)
 * 特有方法:
 * 		public final void writeObject(Object obj)将指定的对象写入 ObjectOutputStream。
 * 反序列化构造方法:
 * 		public ObjectInputStream(InputStream in)
 * 特有方法:
 * 		public final Object readObject()从 ObjectInputStream 读取对象
 * */
public class Text1 {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		Student s1 = new Student("张三",12);
		Student s2 = new Student("李四",13);
		//创建序列化对象
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:\\Student.txt"));
		oos.writeObject(s1);
		oos.writeObject(s2);
		oos.flush();
		oos.close();
		//创建反序列化对象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:\\Student.txt"));
//		Object obj = null;
//		while((obj = ois.readObject())!=null) {
//			System.out.println(obj);	
//		}
//		ois.close();       出现异常 java.io.EOFException
		Object o1 = ois.readObject();//一次读取一个对象
		Object o2 = ois.readObject();
		System.out.println(o1);
		System.out.println(o2);
		ois.close();
	}
}

package org.westos.IO流中序列化与反序列化;

import java.io.Serializable;

public class Student implements Serializable{

	private static final long serialVersionUID = -6946702713406896449L;
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
		super();
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
		
}


猜你喜欢

转载自blog.csdn.net/ws1995_java/article/details/80439779
今日推荐