【问题标题】:Error when trying to write an object to a file in libgdx尝试将对象写入 libgdx 中的文件时出错
【发布时间】:2015-11-20 03:50:13
【问题描述】:

我不断收到此错误。我正在尝试将一个对象保存到 libGDX 中的文件中。我首先创建文件,然后创建一个新的高分并保存它。但它没有用,我尝试让 Score 类实现可序列化并使 score 对象瞬态。两者都没有工作。我尝试在 libGDX 上运行桌面版本。

java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: com.bayanijulian.covertpony.save.Score
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at com.bayanijulian.covertpony.save.SaveHandler.load(SaveHandler.java:35)

还有我的课。

package com.bayanijulian.covertpony.save;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.bayanijulian.covertpony.TSIEngine;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SaveHandler{
    public static void save(){
        FileHandle file = Gdx.files.local("score.txt");

    try{
        ObjectOutputStream scoreOutput = new ObjectOutputStream(file.write(false));
        scoreOutput.writeObject(TSIEngine.score);
        scoreOutput.close();
    }
    catch (Exception e){
        //TODO fix crash
        e.printStackTrace();

    }
}
public static void load(){
    FileHandle file = Gdx.files.local("score.txt");

    try{
        if(!file.exists()){
            file.file().createNewFile();
            TSIEngine.score = new Score("3:00","you");
            save();
        }
        ObjectInputStream scoreInput = new ObjectInputStream(file.read());
        TSIEngine.score = (Score) scoreInput.readObject();
        scoreInput.close();
    }
    catch (Exception e){
        //TODO fix crash
        e.printStackTrace();

    }
}


}

这是我尝试写入文件的 Score 对象。

package com.bayanijulian.covertpony.save;

import java.io.Serializable;

public class Score implements Serializable{
private String time;
private String name;

public Score(String time, String name) {
    this.time = time;
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}
}

感谢您的宝贵时间!任何帮助是极大的赞赏。我一直坚持这一点。我只想保存一个高分。

【问题讨论】:

  • 您的代码对我来说很好。确保在再次测试之前删除旧文件,因为它可能会在实现 Serializable 之前尝试加载旧的无效版本的分数。
  • 我实际上做了更多的测试。是的,你是对的,代码确实有效。但是当我在加载后尝试从分数对象中读取时,它会出错,因为它说它是一个空对象。
  • 删除它创建的文件并重新写入后,它现在可以工作了。谢谢

标签: java android file io libgdx


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2013-08-10
    相关资源
    最近更新 更多