【发布时间】: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 文件,您可以在其中每行放置一个对象,并用逗号(或分号,在某些语言环境中可能更好)分隔它们的属性值。