Java对象流与序列化学习

对象流与序列化

对象流有两个类

  • ObjectOutputStream:将java对象的基本数据类型和图形写入OutputStream
  • ObjectInputStream:对以前使用ObjectOutputStream写入的基本数据和对象进行反序列化。

序列化一组对象

同时序列化多个对象时,反序列化也必须按顺序操作,如果想要序列化一组对象该如何操作呢?

  • 序列化一组对象可采用:对象数组的形式,因为对象数组可以向Object进行转型操作。

transient关键字

  • 如果用transient声明一个实例变量,当对象存储时,它的值不需要维持。

能序列化的要求

  • 如果一个类创建的对象,需要被序列化,那么该类必须实现Serializable接口。
  • Serializable接口是一个标记接口,没有任何定义。
  • 如果对象没有实现该接口,会抛出java.io.NotSerializableException

什么时候需要被序列化呢?

  • 把文件保存到文件中,存储到物理介质
  • 对象需要在网络上传输

示例代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import org.junit.Test;


public class ObjectStreamDemo {

	/**
	 * 对象反序列化,将对象从文件读到程序
	 */
	@Test
	public void readObject() {
		File file = new File("F:/dog.obj");
		try {
			InputStream in = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(in);

			Dog dog = (Dog) ois.readObject();
			System.out.println(dog);
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}// readObject

	/**
	 * 对象序列化:实际写入的是类名、属性名、属性类型、属性值等
	 * 将对象写入到文件
	 */
	@Test
	public void writeObject() {
		Dog dog = new Dog("Tom", "男", 2);
		File file = new File("F:/dog.obj");

		try {
			OutputStream out = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(out);

			oos.writeObject(dog);
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}// writeObject
}

需要被序列化的Dog类,必须实现标记接口Serializable

class Dog implements Serializable {

	// 序列号,保证读取时的编号和存储时的一致,方能读取
	private static final long serialVersionUID = -3094355583246045443L;
	private String name;
	private String sex;
	private int age;
	private transient int id;// 在序列化时被忽略

	public Dog() {}
	public Dog(String name, String sex, int age) {
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	@Override
	public String toString() {
	return "Dog [name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
原文地址:https://www.cnblogs.com/zxfei/p/10877510.html