【问题标题】:Serialized Object File Output is empty序列化对象文件输出为空
【发布时间】:2015-02-17 23:15:29
【问题描述】:

我正在尝试创建一个文件来存储我正在制作的游戏的高分。我正在使用序列化程序将我的数组写入文件。该文件是在运行我的代码时创建的,但该文件为空(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();
        }

    }
}

【问题讨论】:

  • 对于任何可能对我的问题投反对票的人,如果我的问题有问题,我很抱歉。我会很感激有反馈告诉我我的问题出了什么问题,而不是仅仅反对它。这样我以后的问题就不会犯同样的错误了。
  • FileOutputStream f = new FileOutputStream("bestTimes.txt"); f.close(); - 这将打开文件并删除其内容,然后再次将其关闭。所以你成功地写入了文件,然后你什么都没有覆盖它。
  • 很抱歉,由于对上一个问题的答案有误解,所以我输入了那段代码。
  • @kb400 我稍微缩短了你的示例代码,如果它显示一两个问题,重复十几条示例记录没有意义。如果您不需要滚动,这样可以更快地发现问题。
  • @eckes 谢谢。这确实让事情变得更容易了。

标签: java arrays file serialization


【解决方案1】:

当然是空的。您在 finally 块中创建了一个新的。

只需删除该代码。

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2016-04-29
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多