码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA之序列化A

时间:2015-05-08 12:51:17      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

package SwingGui.sky.com;
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", "bix 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();
        }
        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();
        }
    }

}





package SwingGui.sky.com;
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;
    }

}

技术分享

Game.ser内容(基本看不明白):

 sr SwingGui.sky.com.GameCharacter酭锕?胅 I powerL typet Ljava/lang/String;[ weaponst [Ljava/lang/String;xp 2t Elfur [Ljava.lang.String;V玳{G xp t bowt swordt dustsq ~ 萾 Trolluq ~  t
bare handst bix axsq ~ xt Magicianuq ~  t spellst invisibility

JAVA之序列化A

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4487130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!