【问题标题】:What's the easiest way to store objects/a map filled with objects in a file?在文件中存储对象/充满对象的地图的最简单方法是什么?
【发布时间】:2019-04-02 17:24:40
【问题描述】:

我对 Java 比较陌生,从未将某些内容保存到文件中。我想知道初学者在文件中存储和读取用户定义对象的最简单方法是什么。我已经设法将它们放入地图中,现在我必须将此地图保存在某种文件中。我知道有不同的方法可以做到这一点,但是您推荐哪种数据类型和方法? 以及如何从文件中获取单个对象而不是“所有内容”?

在这里你可以看到我的对象和我将创建的对象放入的地图。

public static void main(String[] args) {

Question number1 = new Question("What is the right answer?",
        new String[] { "1", "2", "3", "4" }, 3, 1.0);
}

public class Question {

public String question;
public String[] answers;
public int solution;
public double priority;
static int counter;
public static Map<Integer, Question> Database = new TreeMap<Integer,Question>();

public Question(String que, String[] ans, int sol, double prio){
this.question = que;
this.answers = ans;
this.solution = sol;
this.priority = prio;
Database.put(++counter, this);

}

【问题讨论】:

  • 一个简单的建议可能是一个 csv 文件,您可以在其中每行放置一个对象,并用逗号(或分号,在某些语言环境中可能更好)分隔它们的属性值。

标签: java object save


【解决方案1】:

您可以使用serialization 将您的对象保存到文件中。 Java 内置了序列化功能,但您也可以使用 kryo 等库将地图保存为 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2020-11-23
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2011-01-24
    • 2010-12-29
    • 2010-09-15
    相关资源
    最近更新 更多