JavaIO(七) 对象流

对象流是用于将内存中的对象序列化后存于文件中,或将文件中的数据反序列化为对象

新建一个Person类,一个类要想序列化必须实现Serializable 接口

package com.mike.io.eg;

import java.io.Serializable;

/**
 * @author mike
 * @date 2020-11-26
 * @desc 被序列化对象类
 */
public class Person implements Serializable {
	private int id;
	private String name;
	private int age;

	public Person() {

	}

	public Person(int id,String name,int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。
主要有一个常用方法: void writeObject(Object obj) 将对象写入文件

package com.mike.io.eg;

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

/**
 * @author mike
 * @date 2020-11-28
 * @desc 测试序列化对象
 */
public class ObjectOutputStreamDemo {
	public static void main(String[] args) {
		//定义对象流
		ObjectOutputStream oos = null;
		//创建对象流
		try {
			oos = new ObjectOutputStream(new FileOutputStream("F:\person.txt"));
			oos.writeObject(new Person(10001,"mike",26));
			oos.writeObject(new Person(10002,"jeef",23));
			oos.flush();
			System.out.println("序列化成功");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


	}
}

ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。
主要有一个方法: Object readObject() 将对象从文件读出

package com.mike.io.eg;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
/**
 * @author mike
 * @date 2020-11-28
 * @desc 测试对象反序列化
 */
public class ObjectInputStreamDemo {
	public static void main(String[] args) {
		//定义反序列化对象
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream("F:\person.txt"));
			Person person1 = (Person) ois.readObject();
			Person person2 = (Person) ois.readObject();
			System.out.println(person1);
			System.out.println(person2);
			System.out.println("反序列化成功");
		}catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

输出结果

原文地址:https://www.cnblogs.com/gy1010/p/14054021.html