-1
我试图创建一个存储我正在制作的游戏的高分的文件。我正在使用序列化程序将我的数组写入文件。该文件在运行我的代码时创建,但文件为空(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();
}
}
}
对于任何人可能会低估我的问题,我很抱歉,如果我的问题做错了。我很感谢反馈,告诉我我的问题有什么问题,而不是仅仅对其进行评估。这样我就不会在未来的问题上犯同样的错误。 – kb4000 2015-02-17 23:39:04
'FileOutputStream f = new FileOutputStream(“bestTimes.txt”); f.close(); ' - 这将打开文件并删除其内容,然后再次关闭它。所以你成功地写了这个文件,然后你没有任何东西覆盖它。 – immibis 2015-02-17 23:44:21
抱歉,由于误解了上一个问题的答案,所以我放入了这段代码。 – kb4000 2015-02-17 23:45:46