シリアル化されたObjectOutputStreamオブジェクトは、Serializableインターフェイスを実装するクラスのオブジェクト(Student sなど)でwriteObject(Student s)を呼び出すときに、writeObject(os)を呼び出します。

学生クラス

package com.wgd.io;`在这里插入代码片`
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private transient int age;//transient关键字让age不会被jvm虚拟机默认序列化,但可以自己进行序列化
public Student(){	
}
@Override
public String toString() {
	return "Student [name=" + name + ", age=" + age + "]";
}
public Student(String name, int age) {
	super();
	this.name = name;
	this.age = 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;
}
/**可以对transient修饰的变量序列化,不写 这个函数即默认序列化
 * 自定义序列化
 * @param s
 * @throws java.io.IOException
 */
private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
	s.defaultWriteObject();//把虚拟机能默认序列化的元素序列化
	s.writeInt(age);//将transient修饰的age序列化
}
/**对transient修饰的进行反序列化
 * 自定义反序列化
 * @param s
 * @throws java.io.IOException
 * @throws ClassNotFoundException
 */
private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException{
	s.readObject();//把虚拟机能默认反序列化化的元素反序列化
	this.age=s.readInt();//将transient修饰的age反序列化
}
}

シリアル化クラスのテスト

package com.wgd.io;

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

public class ObjectSerializable {
	public static void main(String[] args)throws IOException {
//对象通过ObjectOutputStream序列化,即将object转换成字节序列
		//通过ObjectInputStream反序列化
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("e:\\test\\objectSerializable.txt"));
		Student s=new Student("张三",20);
		/**
		 **** 这个最后的oos.writeObject(s);在实现的过程中,
		 * 会通过反射在s中寻找方法名为writeObject,
		 * 参数为ObjectOutputStream的方法,
		 * 如果找到了就会调用s.writeObject(oos)的方法;
		 * 没找到的话会使用默认的实现,
		 * 这种情况下你的这个类中的age字段由于是transient的就会丢失掉。
		 * 反过来读取对象的时候也是这样的。***
		 */
		oos.writeObject(s);
		oos.flush();
		oos.close();
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream("e:\\test\\objectSerializable.txt"));
		try {
			System.out.println((Student)ois.readObject());
			ois.close();
		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}

おすすめ

転載: blog.csdn.net/m0_37959155/article/details/83793232