序列化和反序列化不会读取和保存错误

时间:2015-06-23 13:47:29

标签: java object serialization deserialization

我正在尝试将对象保存到文件中并稍后加载它。

我的存档游戏课程

    /**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Level;
import java.io.*;
import Creatures.Player;

public class SaveGame implements java.io.Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 8292780140120605181L;

    /**
     * starts new game with new Player
     */
    public void newGame() {
        Player p = new Player();
        Crawler c = new Crawler();
        try {
            c.game(p);
        } catch (IOException ex) {
            System.out.println("IO Exception");
            ex.printStackTrace();
        }
    }

    /***
     * loads the safed player using deserializing
     * starts new game with existing player 
     */
    public void loadGame() {
        try {
            FileInputStream fileIn = new FileInputStream("tmp/player.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Player p = (Player) in.readObject();

            Crawler cl = new Crawler();
            if (p != null) {
                System.out.println(p.getHp() + "hp");
                System.out.println(p.getAtk() + "atk");
                System.out.println(p.getGold() + "Gold");
                cl.game(p);
                System.out.println("hi2");
            } else {
                Start sgs = new Start();
                sgs.chooseGame();
            }

            in.close();
            fileIn.close();
        } catch (IOException i) {
            System.out.println("Kein Speicherstand gefunden.");
            return;
        } catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFound");
        }
    }

    /**
     * safes the player using serializing
     * @param p Player
     */
    public void saveGame(Player p) {
        OutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream("tmp/player.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(p);
            out.close();
            fileOut.close();
            System.out.printf("Serialized data is saved in /tmp/player.ser ");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

我的角色等级:

package Creatures;

import List_Tree.Inventar;
import java.util.Objects;
import List_Tree.*;

public class Character {
    /**
     * The constant ATTACK_NORMAL.
     */
    public static final int ATTACK_NORMAL = 0;
    /**
     * The constant ATTACK_SPECIAL.
     */
    public static final int ATTACK_SPECIAL = 1;
    /**
     * The Max hp.
     */
    private int maxHp;
    /**
     * The Hp.
     */
    private int hp;
    /**
     * The Atk.
     */
    private int atk;
    /**
     * The Hit chance.
     */
    private double hitChance;
    /**
     * The Inventar.
     */
    private List<Item> inventar;
    /**
     * The Questlog
     */
    private List<Quest> questlog;
    /**
     * The Gold.
     */
    private double gold;

    /**
     * Instantiates a new Character.
     *
     * @param maxHp     the max hp
     * @param atk       the atk
     * @param hitChance the hit chance
     * @param gold      the gold
     */
    public Character(int maxHp, int atk, double hitChance, double gold) {
        this.maxHp = maxHp;
        this.hp = maxHp;
        this.atk = atk;
        this.hitChance = hitChance;
        inventar = new Inventar();
        questlog = new Questlog();
        this.gold = gold;
    }
    /**
     * Instantiates a new Character
     * no params
     */
    public Character() {
    }

    /**
     * Gets hit chance.
     *
     * @return the hit chance
     */
    public double getHitChance() {
        return hitChance;
    }

    /**
     * Sets hit chance.
     *
     * @param hitChance the hit chance
     */
    public void setHitChance(double hitChance) {
        if (hitChance >= 0 && hitChance <= 1) {
            this.hitChance = hitChance;
        }
    }

    /**
     * Gets hp.
     *
     * @return the hp
     */
    public int getHp() {
        return hp;
    }

    /**
     * Sets hp.
     *
     * @param hp the hp
     */
    public void setHp(int hp) {
        if (hp > maxHp) {
            this.hp = maxHp;
        } else if (hp < 0) {
            this.hp = 0;
        } else {
            this.hp = hp;
        }
    }

    /**
     * Gets max hp.
     *
     * @return the max hp
     */
    public int getMaxHp() {
        return maxHp;
    }

    /**
     * Gets atk.
     *
     * @return the atk
     */
    public int getAtk() {
        return atk;
    }

    /**
     * Sets atk.
     *
     * @param atk the atk
     */
    public void setAtk(int atk) {
        this.atk = atk;
    }

    /**
     * Take damage.
     *
     * @param damage the damage
     *
     * @return the int
     */
    public int takeDamage(int damage) {
        return takeDamage(damage, ATTACK_NORMAL);
    }

    /**
     * Take damage.
     *
     * @param damage     the damage
     * @param attackType the attack type
     *
     * @return the damage
     */
    public int takeDamage(int damage, int attackType) {
        setHp(getHp() - damage);
        return damage;
    }

    /**
     * Is defeated.
     *
     * @return true, wenn man besiegt ist
     */
    public boolean isDefeated() {
        return getHp() == 0;
    }

    /**
     * Attack int.
     *
     * @param c the enemy
     *
     * @return -1, fuer Verfehlt, sonst den angerichteten Schaden
     */
    public int attack(Character c) {
        if (Math.random() <= hitChance) {
            int damage = (int) (atk * (Math.random() + 1.0));
            return c.takeDamage(damage);
        } else {
            return -1;
        }
    }

    /**
     * Loot void.
     *
     * @param corpse the corpse
     */
    public void loot(Character corpse) {
        gold += corpse.gold;
        corpse.gold = 0;

        while (!corpse.inventar.isEmpty()) {
            inventar.insert(corpse.inventar.firstItem());
            corpse.inventar.delete();
        }
    }

    /**
     * Gets inventar.
     * 
     * @return the inventar
     */
    public List<Item> getInventar() {
        return inventar;
    }

    /**
     * gets the questlog from the character
     * @return questlog
     */
    public List<Quest> getQuestlog() {
        return questlog;
    }

    /**
     * sets the Questlog to the value given
     * @param ql List<Quest>
     */
    public void setQuestlog(List<Quest> ql) {
        this.questlog = ql;
    }

    /**
     * sets the questlog of the character to a new, empty questlog
     */ 
    public void setNewQuestlog() {
        this.questlog = new Questlog();
    }

    /**
     * adds item to inventar
     * @param x item youll add to the inv
     */
    public void addToInventar(Item x) {
        Objects.requireNonNull(inventar);
        inventar.insert(x);
    }

    /**
     * deletes item from inventar
     * @param x the item youll delete
     */
    public void deleteFromInventar(Item x) {
        Objects.requireNonNull(inventar);
        inventar.delete(x);
    }

    /**
     * adds quest to the questlog
     * @param x the quest youll add
     */
    public void addToQuestlog(Quest x) {
        Objects.requireNonNull(questlog);
        questlog.insert(x);
    }

    /**
     * deletes quest from the questlog
     * @param x the Quest you want to delete
     */
    public void deleteFromQuestlog(Quest x) {
        Objects.requireNonNull(questlog);
        questlog.delete(x);
    }

    /**
     * Getter for the character's gold.
     * @return the gold
     */
    public double getGold() {
        return gold;
    }

    /**
     * Sets gold.
     * @param i the value you want to set
     */
    public void setGold(double i) {
        this.gold = i;
    }

    /**
     * Fill character inventory
     */
    public void fillInventory() {

        Inventar tmp = Inventar.getTreeAllItems();
        int k = (int) (10 * Math.random());
        for (int i = 0; i < k; i++) {
            int l = (int) ((Inventar.getTreeAllItems().getItemsInList()) * Math.random());

            if (this.getInventar().isEmpty()) {
                this.getInventar().append(Inventar.getTreeAllItems().getItem(l));
            } else {
                this.getInventar().insert(Inventar.getTreeAllItems().getItem(l));
            }

        }
    }
}

方法正在运行并且文件被创建,但它只是奇怪的东西,那里有什么。这里是保存文件:

  

¬ísrCreatures.Playersß™'我的api apRegenI healingPowerI   maxApI remainingItemUsesxp F F F

通常我应该得到2个整数,2个双打和2个链式列表。

1 个答案:

答案 0 :(得分:0)

尝试此代码并检查其是否有效。

<强> User.java

import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

源代码(SerializeObject.java)

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();

        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);

        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

源代码(DeSerializeObject)

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}