java - 序列化对象文件输出为空

标签 java arrays file serialization

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

相关文章:

java - 蓝牙打印在不同设备上从 Socket 抛出 IOException

java - 如何将 ASCII 编码的 SHA1 哈希(40 字节十六进制字符串)从 40 字节转换为 20 字节?

arrays - 在数组中存储字典 ArrayLiterialConversion 错误

c++ - 错误 : size of array ‘u’ has non-integral type ‘double’ |

java - 使用 servlet 上传文件,但仅在运行时

python - 调用 python 脚本时,它是否将完整的脚本加载到终端/命令提示符中?

java - 如何使用 Java 解析来自第三方服务器的 SOAP 响应

java - 添加帮助内容,使用命令框架搜索帮助

python - 基本 Numpy 数组值赋值

c++ - 有没有一种简单的方法可以判断文件流是否打开了目录而不是文件?