Java对象序列化与对象持久化:利用对象流实现给定对象与字节之间的相互转换

版权声明:转载注明来源。Keep Learning and Coding. https://blog.csdn.net/a771581211/article/details/88567717

首先定义测试类对象Person:

package day07;
/**
 * 该类用于测试作为对象流读写对象使用
 * 
 * 当一个类需要被对象流读写时,该类必须实现
 * java.io.Serializable接口。
 * @author kaixu
 *
 */

import java.io.Serializable;
import java.util.List;

public class Person implements Serializable{
	private String name;
	private int age;
	private String gender;
	private List<String> otherInfo;
	
	public Person(){
		
	}

	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 String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public List<String> getOtherInfo() {
		return otherInfo;
	}

	public void setOtherInfo(List<String> otherInfo) {
		this.otherInfo = otherInfo;
	}
	
	public String toString(){
		return name+","+age+","+gender+","+otherInfo;
	}
}

对象输出流:又称为对象序列化,将给定对象转换为一组字节后写出。

package day07;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 对象流
 * 对象流是一对高级流,作用是方便读写java中的对象。
 * java.io.ObjectOutputStream
 * 	
 * @author kaixu
 *
 */
public class OOSDemo {

	public static void main(String[] args) throws IOException {
		Person p = new Person();
		p.setName("凡弟弟");
		p.setAge(10);
		p.setGender("女");
		
		List<String> otherInfo = new ArrayList<String>();
		otherInfo.add("是一个弟弟");
		otherInfo.add("是一个辣鸡");
		p.setOtherInfo(otherInfo);
		
		FileOutputStream fos = new FileOutputStream("person.obj");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		/*
		 * ObjectOutStream的writeObject方法可以将给定对象转换为一组字节后写出
		 * 这些字节比该对象实际内容要大,因为除了数据外还有结构等描述信息。
		 * 
		 * 下面的代码实际上经历了两个操作:
		 * 1.OOS将Person对象转换为一组字节
		 * 	   将一个对象转换为一组字节的过程称为:对象序列化
		 * 
		 * 2.再通过FOS将这组字节写入到硬盘
		 *   将该对象转换的字节写入到硬盘做长久保存的过程称为:对象持久化
		 */
		
		oos.writeObject(p);
		System.out.println("写出对象完毕!");
		oos.close();
	}

}

对象输入流:又称为对象反序列化,读取一组字节并还原为对象。

package day07;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.imageio.spi.IIOServiceProvider;

/**
 * java.io.ObjectInputStream
 * 对象输入流,作用是可以进行对象反序列化,读取一组字节并还原为对象。
 * OIS读取的字节必须是由OOS将对象序列化后得到的字节,否则会抛出异常。
 * @author kaixu
 *
 */
public class OISDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream("person.obj");
		ObjectInputStream ois = new ObjectInputStream(fis);
		//对象反序列化
		
		Person p = (Person)ois.readObject();
		System.out.println(p);
		
		ois.close();
	}

}

猜你喜欢

转载自blog.csdn.net/a771581211/article/details/88567717