我正在尝试创建一个文件来存储我正在制作的游戏的高分。我正在使用序列化器将数组写入文件。该文件是在运行我的代码时创建的,但该文件是空的(0 字节)。我没有收到任何错误。谁能告诉我为什么该文件不包含我的数据?
public class BestTimes implements Serializable
{
BestTimes[] beginner = new BestTimes[2];
public static void main(String args[]) throws IOException {
BestTimes bestTimes = new BestTimes();
bestTimes.outputToFile();
}
public BestTimes() {
beginner[0] = new BestTimes(1, "John", 10.5);
beginner[1] = new BestTimes(2, "James", 20.3);
}
public int ranking;
public String playerName;
public double time;
public BestTimes(int r, String p, double t)
{
ranking = r;
playerName = p;
time = t;
}
public void outputToFile() throws IOException {
try(FileOutputStream f = new FileOutputStream("bestTimes.txt")) {
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(beginner);
s.flush();
s.close();
} finally {
FileOutputStream f = new FileOutputStream("bestTimes.txt");
f.close();
}
}
}
最佳答案
当然是空的。您在 finally
block 中创建了一个新的。
只需删除该代码即可。
关于java - 序列化对象文件输出为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573062/