3.14Java学习笔记

序列化和文件的输入/输出

序列化: 将对象的状态消息转化为可以便利存储或者传输的形式的过程。序列化期间,将对象的当前状态写入到临时或者永久存储区。以后可以根据此重新创建当前状态的对象。
序列化存储的方法步骤:

  1. 创建出FileOutputStream
FileOutputStream fileStream=new FileOutputStream("MyGame.ser");
//fileStream为你指定的对象名
//MyGame.ser为你创建的文件名
  1. 创建ObjectOutputStream;
ObjectOutputStream os=new ObjectOutputStream(fileStream);
//此步为创建文件的指引
  1. 写入对象
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
  1. 关闭ObjectOutputStream
os.close();

这是书上的模板,搬运过来。

解序列化的步骤

  1. 创建FileInupStream
FileInputStream fileStream=new FileInputStream("MyGame.ser");
  1. 创建ObjectInputStream
ObjectInputStream os=new ObjectInputStream(fileStream);
  1. 读取对象
Object one=os.readObject();
Object two=os.readObject();
Object three=os.readObject();
  1. 强制转化对象类型
GameCharacter elf=(GameCharacter) one;
GameCharacter troll=(GameCharacter) two;
GameCharacter magician=(GameCharacter) three;
  1. 关闭ObjectInputStream
os.close();

序列化要点

  1. 对象必须实现序列化这个接口才能被序列化,如果父类实现序列化,则子类也自动实现序列化。
    (implements Serializable)。
  2. 当一个实例变量被标记为transient,那么在还原时会被赋予null或者primitive主数据类型的默认值。
  3. 读取对象的顺序必须与写入顺序相同。
  4. readObject()返回的类型是Object,因此需要强制转化。
  5. 静态变量不会被实例化。

我的样例

Serialization_cat类
package study;
import java.io.*;
public class Serialization_cat implements Serializable{
	String name="xiaojiu";
	int age=0;
	public void setname(String n){
		name=n;
	}
	public void setage(int a){
		age=a;
	}
	public static void main(String[] args) {
		Serialization_cat mycat=new Serialization_cat();
		mycat.setage(0);
		mycat.setname("Tom");
		try {
			FileOutputStream fs=new FileOutputStream("Cat.ser");
			ObjectOutputStream os=new ObjectOutputStream(fs);
			os.writeObject(mycat);
			System.out.println(mycat.name+" is "+mycat.age);
			os.close();
		}catch(Exception ex) {
			System.out.println("xxxx");
			ex.printStackTrace();
		}
	}
}

text类
package study;
import java.io.*;
public class text {
	public static void main(String[] args) throws Exception {
		FileInputStream fileStream=new FileInputStream("Cat.ser");
		ObjectInputStream os=new ObjectInputStream(fileStream);
		Object Cat=os.readObject();
		Serialization_cat mycat=(Serialization_cat) Cat;
		System.out.println(mycat.name+" is "+mycat.age);
		os.close();
		//System.out.println(mycat.setname("Tom")+" is "+mycat.setage(1);
	}
}

运行结果
Tom is 0

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值