【问题标题】:Serialization/Deserialization of my custom class and save it to binary file我的自定义类的序列化/反序列化并将其保存到二进制文件
【发布时间】:2016-06-10 13:25:12
【问题描述】:

我在我的项目中声明了一个自定义类:

public class LocationData {

    private Location location;
    private LocalDateTime localDateTime;
    private int heartRate;
    private int calories;
    private int ropeMoves;
    private int dumbbellMoves;
    private int pedalRotations;
    private int wheelRotations;
    private int numberOfSteps;

    public LocationData(Location location, LocalDateTime localDateTime, int heartRate, int calories, int ropeMoves, int dumbbellMoves, int pedalRotation, int wheelRotations, int numberOfSteps) {
        this.location = location;
        this.localDateTime = localDateTime;
        this.heartRate = heartRate;
        this.calories = calories;
        this.ropeMoves = ropeMoves;
        this.dumbbellMoves = dumbbellMoves;
        this.pedalRotations = pedalRotations;
        this.wheelRotations = wheelRotations;
        this.numberOfSteps = numberOfSteps;
    }

    public Location getLocation() {
        return location;
    }

    public LocalDateTime getLocalDateTime() {
        return localDateTime;
    }

    // Other getters

    @Override
    public String toString() {
        return "LocationData[" +
                "\n\tlocation=" + location +
                "\n\tlocalDateTime=" + localDateTime +
                "\n\tcalories=" + calories +
                "\n\theartRate=" + heartRate +
                "\n\tropeMoves=" + ropeMoves +
                "\n\tdumbbellMoves=" + dumbbellMoves +
                "\n\tpedalRotations=" + pedalRotations +
                "\n\twheelRotations=" + wheelRotations +
                "\n\tnumberOfSteps=" + numberOfSteps +
                "]";
    }
}

它代表一个位置加上一些信息。然后我保存ListLocationData 来创建“路线”。

我需要将此列表(称为 location)保存到一个文件中,因为将来用户会要求检索它以创建 GPX 文件。

我认为最好的解决方案是使LocationData 类可序列化,但我不知道如何序列化(然后反序列化)它。所以...我需要了解如何:

  1. 序列化LocationData
  2. 反序列化LocationData
  3. 创建序列化LocationData的列表
  4. 将列表写入文件
  5. 从文件中读取列表

【问题讨论】:

标签: java file serialization deserialization


【解决方案1】:

您需要在类定义中添加implements Serializable,但您不必实现Serializable 的方法——Object 已经有默认实现,Serializable 接口用作声明性。

您还需要确保LocationLocalDateTime 都是可序列化的。

最后,一旦一切就绪,您就可以使用 ObjectInputStream / ObjectOutputStream 来读取和写入您的对象

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2014-01-04
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多