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();
}
}
}
//测试结果--控制台: