java_IO流之ObjectInputStream与ObjectOutputStream的使用,序列化与反序列化多个对象

package test01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class stu {
	// 注意此处为静态类
	// 类可序列化,要实现Serializable
	static class student implements Serializable {
		private String name;
		private String tel;
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public student(String name, String tel) {
			this.name = name;
			this.tel = tel;

		}

		public String getName() {
			return name;
		}

		public String getTel() {
			return tel;
		}

		public void setName(String name) {
			this.name = name;
		}

		public void setTel(String tel) {
			this.tel = tel;
		}

		// 打印的内容
		public String toString() {
			// TODO 自动生成的方法存根
			return "name:" + name + "    " + "tel:" + tel + ":";
		}
	}

	public static void main(String args[]) {
		// 将对象写入至文本
		try {
			// 创建输出对象
			FileOutputStream fileOutputStream01 = new FileOutputStream(
					"D:\\name.dat");
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(
					fileOutputStream01);
			// 写出对象
			objectOutputStream.writeObject(new student("z1", "1111"));
			objectOutputStream.writeObject(new student("z2", "2222"));
			objectOutputStream.writeObject(new student("z3", "3333"));
			objectOutputStream.writeObject(new student("z4", "4444"));
			// 要反序列化多个对象需要一个空对象作为标识符
			objectOutputStream.writeObject(null);
			// 刷新缓冲区
			objectOutputStream.flush();
			// 关闭流
			objectOutputStream.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		// 对象从文本中读入
		try {
			// 创建对象输入流
			FileInputStream fileInputStream = new FileInputStream(
					"D:\\name.dat");
			ObjectInputStream objectInputStream = new ObjectInputStream(
					fileInputStream);
			// 读取对象
			Object object;
			// 循环打印对象内容,并查验是否对象是否为空
			while ((object = (student) objectInputStream.readObject()) != null) {
				System.out.println(object);
			}
			objectInputStream.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}
}

你可能感兴趣的:(java,序列化,javaIO流)