读取文件时出现NullPointerException

时间:2014-03-31 01:52:42

标签: java

当我加载这个文件时,我总是得到NullPointerException。我尝试了很多东西,我找不到解决方法。当我保存时,我使用了Game对象。

     @Override
        public void load(Superhero aHero,Villain aVillain) throws IOException, ClassNotFoundException {

        ObjectInputStream ois = null;
        FileInputStream fis = null;
        File f = new File("C:\\prog24178\\dcgames.dat");
        Game aGame = new Game(aHero,aVillain);
        try {
            fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            while(true){
                aGame = (Game) ois.readObject();
                System.out.println(aGame);

            }
        } catch(EOFException eof){
            ois.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DcGameController.class.getName()).log(Level.SEVERE, null, ex);
        } 

    }

当我打开文件时,我看到类似的东西:

    ’ sr 
    model.Game      ^r Z gameOverZ heroTurnL theHerot Lmodel/Superhero;L 
    theVillaint Lmodel/Villain;xp  sr model.hero.Batman      ^r Z armedL sidekickq ~ xr model.Superhero      ^r I energyZ secretIdentityL codenamet Ljava/lang/String;L hometownq ~ xr model.Avatar      ^r 
    I agilityI     enduranceI fightingI   hitPointsI  intuitionI psycheI reasonI strengthL     firstNameq ~ L lastNameq ~ xp            W            t  q ~      t Batmant Gotham Citysq ~                                 t Dickt Grayson    ppsr model.villain.Cheetah      ^r  xr 
    model.Villain      ^r I energyZ insaneL codenameq ~ xq ~             b            t   Priscillat Rich    t Cheetah

所以我知道它正在工作,但我想阅读,之后我可以设置我需要使用的设置。

这是我的保存方法:

    @Override
    public void saveGame(Game aGame) {
        File aSaveFile = new File("C:\\prog24178\\dcgames.dat");
        FileOutputStream fos = null;

        if (!aSaveFile.getParentFile().exists()) {
            aSaveFile.getParentFile().mkdir();
        }
        try {
            if (!aSaveFile.exists()) {
                aSaveFile.createNewFile();
            }
            if (aSaveFile.length() > 0) {
                fos = new FileOutputStream(aSaveFile, true);
            } else {
                fos = new FileOutputStream(aSaveFile, false);
            }
            if (oos == null) {
                oos = new ObjectOutputStream(fos);
            }
            oos.writeObject(aGame);
        } catch (FileNotFoundException ex) {

        } catch (Exception x) {
            System.out.println("Something bad happened" + x);
        }
    }

感谢您帮助我解决问题。

1 个答案:

答案 0 :(得分:0)

我认为你应该检查2个问题,

1。fos = new FileOutputStream(aSaveFile, true);
如果aSaveFile已经有一些数据并且你将另一个对象数据附加到aSaveFile,它的数据将会混淆,你将无法将对象带回来。

2。oos.writeObject(aGame);
当你完成writeObject()时,你应该使用oos.flush();

来刷新流缓冲区