存贮和恢复游戏人物

import java.io.*;

public class GameSaverTest
{
	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(IOException ex){ex.printStackTrace();}
		//设定为null因此无法存取堆上的这些对象
		one=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 ex)
		{ex.printStackTrace();}
	}
	
}


import java.io.*;
public class GameCharacter implements Serializable
{
	int power;
	String type;
	String [] weapons;
	public GameCharacter(int p,String t,String [] w)
	{
		power=p;
		type=t;
		weapons=w;	
	}
	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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值