Java序列化应用案例-----存储与恢复游戏人物

GameCharacter类---游戏人物类
package com.Game;

import java.io.Serializable;

public class GameCharacter implements Serializable {
	int power;
	String type;
	String[] weapons;	
	public GameCharacter(int power, String type, String[] weapons) {
		super();
		this.power = power;
		this.type = type;
		this.weapons = weapons;
	}	
	public int getPower() {
		return power;
	}
	public String getType() {
		return type;
	}	
	public String getWeapons() {
		String weaponList = "";
		for(int i = 0;i < weapons.length;i++){
			weaponList += weapons[i]+"";
		}
		return weaponList;
	}	
}
//游戏测试类
package com.Game;

import java.io.*;


//存储于回复游戏人物
public class GameSaveTest {
	public static void main(String[] args) {
		//创建人物
		GameCharacter one = new GameCharacter(50, "Elf", new String[]{"bow","sword","dust"});
		GameCharacter two = new GameCharacter(200, "Troll", new String[]{"bare hands","big ax"});
		GameCharacter three = new GameCharacter(120, "Magician", new String[]{"spells","invisibility"});
		//假设此处有改变人物状态值的程序代码
		try {
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser"));
			os.writeObject(one);
			os.writeObject(two);
			os.writeObject(three);
			os.close();			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		one = null;  //设定成null,因此无法存取堆上的这些对象,,用于模拟重启游戏环境。
		two = null;
		three = null;
		
		try {
			ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser"));
			GameCharacter oneRestore = (GameCharacter) is.readObject();
			GameCharacter twoRestore = (GameCharacter) is.readObject();
			GameCharacter threeRestore = (GameCharacter) is.readObject();
			
			System.out.println("one's type:"+ oneRestore.getType());
			System.out.println("two's type:"+ twoRestore.getType());
			System.out.println("three's type:"+ threeRestore.getType());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		
		
		
		
		
	}
}

//测试结果--控制台:

关注公众号:工控技术之家,可留言提问相关问题,有需要可发送源代码

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值