Java序列化EOF异常

时间:2016-12-08 02:30:06

标签: java serialization io stream

我正在尝试为我正在制作的游戏写一个高分等级,所以我将得分的名称和得分的值写入得分等级,然后我检查HighScore课程是否在高分。 但是我在序列化中遇到了一个简单的问题,但我不确定错误是什么。这是代码:

book

分数类如下:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class HighScore<T extends Serializable & Comparable<T>> implements
        Serializable, Iterable<T> {

    private int size = 3;
    private ArrayList<T> list;
    private static final String HS_FILE = "resources/High_Scores.txt";
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    public String name;

    public HighScore(int size) {
        this.size = size;
        list = new ArrayList<>(size);
    }

    public boolean add(T val) throws IOException, ClassNotFoundException {

        readFile();
        boolean addWorks = list.size() < size || list.get(list.size()
                - 1).compareTo(val) < 0;
        if (addWorks) {
            list.add(val);
            Collections.sort(list, Collections.reverseOrder());
            if (list.size() > size) {
                list.remove(size);
            }
            updateFile();
            int i = 1;
            for (Iterator<T> it = list.iterator(); it.hasNext();) {
                Score n = (Score) it.next();
                System.out.println(i + ": " + n.name + ", " + n.score + " points ");
                i++;
            }
        }
        return addWorks;
    }

    private void readFile() throws IOException, ClassNotFoundException {
        ois = new ObjectInputStream(new FileInputStream(HS_FILE));
        list = (ArrayList<T>) ois.readObject();
    }

    private void updateFile() throws FileNotFoundException, IOException {
        oos = new ObjectOutputStream(new FileOutputStream(HS_FILE));
        oos.writeObject(list);
    }

    @Override
    public Iterator<T> iterator() {
        return list.iterator();
    }
}

输出显示的错误是:

import java.io.Serializable;

public class Score implements Serializable, Comparable<Score> {

String name;
int score;

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

public String getName() {
    return name;
}

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

public int getScore() {
    return score;
}

public void setScore(int score) {
    this.score = score;
}

@Override
public String toString() {
    return "Score{" + "name=" + name + ", score=" + score + '}';
}

@Override
public int compareTo(Score that) {
    return this.score - that.score;
}

}

任何帮助都会很棒!!谢谢!

1 个答案:

答案 0 :(得分:0)

我假设您正在尝试序列化/反序列化分数?你能检查它是否实现Serializable?你可以通过分数代码